Home » Python » Python programs

Python program to find sum of all digits of a number

Here, we are going to learn how to find the sum of all digits of a given number in Python programming language?
Submitted by IncludeHelp, on April 03, 2020

Here, we are implementing a python program to find the sum of all digits using the recursion method.

Example:

    Input: 0
    Output: 0

    Input: 12345
    Output: 15

    Input: 5678379
    Output: 45

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.