Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that shall read a 4-character string and display the sum of all

ID: 673983 • Letter: W

Question

Write a program that shall read a 4-character string and display the sum of all decimal digits in the string, if any. If the string has no decimal digits, the program shall report 0. For example, for the string "A77B" the program shall display 14, and for the string "MEOW" - 0. Hints: A character is a decimal digit if it is between '0' and '9' (inclusive). A character is between characters A and B, if its charcode is between the charcodes of A and B. The decimal value of a decimal digit is the difference between its charcode and the charcode of '0' (Check the value of ord ( ' 7 ' ) -ord ( ' 0 ' ) !)

Explanation / Answer

#!/usr/bin/python
inputString = raw_input('Enter a 4-digit string: ');
sum = 0;
for letter in inputString:
if(letter.isdigit()):
sum = sum + ord(letter) - ord('0');
print 'The sum of the digits in the given string',inputString,' is ',sum;   

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote