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.
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)
Input a four digit numbers: 5245 The sum of digits in the number is 16
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: foo() except Exception: print("Exception occured") else: print("Exception didnt occur") finally: print("Always gets here")
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework