Sum of Digits in a String
Write a program that asks the user to enter a series of single-digit numbers with nothing separating them. The program should display the sum of all the single digit numbers in the string. For example, if the user enters 2514, the method should return 12, which is the sum of 2, 5, 1, and 4.
Sum of Digits in a String Program Code:
def sumOfDigits(number):
total_sum = 0
# Iterate over each character in the string
for char in number:
# Convert the character to an integer and add it to the sum
digit = int(char)
total_sum += digit
return total_sum
#Prompt and read the user to enter a series of single-digit
#numbers with nothing separating them
number = input("Enter a series of single-digit numbers: ")
# Calculate and display the sum of all the
# single digit numbers in the string
total = sumOfDigits(number)
print("Sum of the single-digit numbers:",total)
Executed Output 1:
Enter a series of single-digit numbers: 2514
Sum of the single-digit numbers: 12
Executed Output 2:
Enter a series of single-digit numbers: 5555
Sum of the single-digit numbers: 20