Q:

Python program to find sum of all digits of a number

belongs to collection: Python basic programs

0

Example:

    Input: 0
    Output: 0

    Input: 12345
    Output: 15

    Input: 5678379
    Output: 45

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

# Python program to find the 
# sum of all digits of a number

# function definition
def sumDigits(num):
  if num == 0:
    return 0
  else:
    return num % 10 + sumDigits(int(num / 10))

# main code
x = 0
print("Number: ", x)
print("Sum of digits: ", sumDigits(x))
print()

x = 12345
print("Number: ", x)
print("Sum of digits: ", sumDigits(x))
print()

x = 5678379
print("Number: ", x)
print("Sum of digits: ", sumDigits(x))
print()

Output

Number:  0
Sum of digits:  0

Number:  12345
Sum of digits:  15

Number:  5678379
Sum of digits:  45

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python basic programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Print number with commas as thousands separators i... >>
<< Python program to print the version information...