SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
More About Strings
Exercise:
Programming Exercises
Question:2 | ISBN:9780132576376 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.