a) sum = 0
for letter in '12345' :
sum = sum + int(letter)
print('sum = ', sum)
Write a program which reads a string containing any characters from the user and prints the sum of the digits in the string. For example, if the string from the user is "I want 3 oranges and 24 bananas', then the output would be 9, since 3 + 2 + 4 = 9. Note that a character C is a digit if '0' < C < '9' alternatively, you can use C.isdigit().
b) read a string S from the user which is a sequence of decimal numbers separated by commas, e.g., S = "1.23,2.4,3.123". Print the sum of the numbers, which for this example is the sum of 1.23 + 2.4 + 3.123 = 6.753. Note that S.split(',') is a list of the substrings: ['1.23', '2.4', '3.123'], which were separated by commas. Another way to pick out the numbers is using an accumulator which stops accumulating at each comma and at the end of the string.
s = input("Enter input: ") sum = 0 for letter in s: if letter.isdigit(): sum = sum + int(letter) print('sum = ', sum)
####################################
s = input("Enter input: ") sum = 0 for letter in s.split(","): sum = sum + float(letter) print('sum = ', sum)
Get Answers For Free
Most questions answered within 1 hours.