Programming Problems · Q4
Q.Input a string having some digits. Write a function to return the sum of digits present in this string.
Puducherry TnboardTextbookSubjective· 3mImportance★★★★★est
92% · 12/13 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Walk the string once; ch.isdigit() picks out digit characters, int(ch) converts each to its numeric value, and a running total accumulates the sum.
Idea. The string mixes letters, digits and possibly symbols. A digit inside a string is a character ('7'), not a number, so two things are needed per character: a test — isdigit() — and a conversion — int(). Everything that is not a digit is skipped.
Algorithm
- Set total = 0.
- For every character ch in the string: if ch.isdigit(), do total += int(ch).
- Return total.
def sumDigits(st):
"""Return the sum of all digits present in string st."""
total = 0
for ch in st:
if ch.isdigit():
total += int(ch) # '7' -> 7
return total
# main program
s = input("Enter a string having digits: ")
print("Sum of digits in the string:", sumDigits(s))
Trace for st = "Class11Python3":
| ch | isdigit()? | total |
|---|---|---|
| C,l,a,s,s | no | 0 |
| 1 | yes | 1 |
| 1 | yes | 2 |
| P,y,t,h,o,n | no | 2 |
| 3 | yes | 5 |
Sample runs
Enter a string having digits: Class11Python3
Sum of digits in the string: 5
Enter a string having digits: a1b2c3d4 …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.