Exercise 63

Write a Python program as function called sum_of_digits() that take a string 's' as parameter and return the sum of digits in the string 's'.

Solution

def sum_of_digits(string):
    """
    This function takes a string as input and returns the sum of all the digits in the string.
    """
    # we initialize a variable called sum to 0
    sum = 0
    #  For each character, we check if it is a digit using the isdigit() method
    for char in string:
        if char.isdigit():
            sum += int(char)
    return sum
# Exemple of use
string = "Python 3.11 is released in 2022"
print(sum_of_digits(string))  # Output: 11




 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 63: Python function which compute the sum of digits of a given string”

Leave a Reply