Input a string having some digits. Write a function to return the sum of digits present in this string.
python #Function to return the sum of digits present in a string def sumDigits(st): total = 0 for character in st: #Check if character is a digit if character.isdigit(): #Convert character to integer and add to total total += int(character) return total #end of function
#Main program st = input("Enter a string: ") result = sumDigits(st) print("Sum of digits in the string is:", result)
Output:
Enter a string: Hello123World Sum of digits in the string is: 6
In this program, a user defined function sumDigits() is created that takes a string as a parameter. A variable total is initialized to 0 to store the sum of digits.
The function uses a for loop to iterate through each character in the string. For each character, the isdigit() method checks if it is a digit. If the character is a digit, it is converted to an integer using int() and added to total.
Finally, the function returns the total sum. The main program accepts a string from the user, calls the function, and displays the result.
Explanation
This question tests the student's understanding of string traversal and character checking. The solution follows the pattern shown in Program 8-1 and Program 8-2 from the textbook, where a user-defined function iterates through each character of a string using a for loop. The isdigit() method is used to identify digit characters, which are then converted to integers using int() before adding to the sum. This approach is consistent with the textbook's methodology of handling strings character by character.
Solution Steps
Step 1: Define a function sumDigits() with string parameter st
Step 2: Initialize total = 0 to store sum of digits
Step 3: Use for loop to iterate through each character in st
Step 4: Check if character is a digit using isdigit() method
Step 5: Convert digit character to integer using int() and add to total
Step 6: Return total after loop ends
Step 7: In main program, input string, call function, and print result