w3resource

Python: Calculate the sum of the digits in an integer

Python Basic: Exercise-68 with Solution

Write a Python program to calculate the sum of the digits in an integer.

Pictorial Presentation:

Calculate the sum of the digits in an integer

Sample Solution:-

Python Code:

num = int(input("Input a four digit numbers: "))
x  = num //1000
x1 = (num - x*1000)//100
x2 = (num - x*1000 - x1*100)//10
x3 = num - x*1000 - x1*100 - x2*10
print("The sum of digits in the number is", x+x1+x2+x3)

Sample Output:

Input a four digit numbers: 5245                                                                              
The sum of digits in the number is 16

Flowchart:

Flowchart: Calculate the sum of the digits in an integer.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to convert pressure in kilopascals to pounds per square inch,a millimeter of mercury (mmHg) and atmosphere pressure.
Next: Write a Python program to sort three integers without using conditional statements and loops.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Try-catch-else construct:

try:
  foo() 
except Exception: 
  print("Exception occured")
else:
  print("Exception didnt occur")
finally:
  print("Always gets here")