ComputerShikshak.com

Python - Sum of Digits of a Number

Problem Statement

Write a program in Python to find the sum of the digits present in an integer number entered by the user.

Brief Description

According to the problem statement we have to write a program in Python that will take an integer value as input from the user through the keyboard and will find the sum of the digits present in that number.

For example, if the user enters 132 as input, the program will generate 6 as output since the number 132 contains the digits 1, 3 and 2 and 1+3+2=6.

Program

				
					num=int(input("Enter a number: "))
tot=0
temp=abs(num)
while temp!=0:
    rem=temp%10
    tot=tot+rem    #OR    tot+=rem
    temp=temp//10    #OR    temp//=10 
print("Sum of the digits present in",num,"is",tot)
				
			

Output

Explanation

In this program:
  • 4 variables namely num, temp, rem and tot are used.
  • Initially 0 is stored in tot.
  • The integer value entered by the user is stored in num.
  • The absolute value corresponding to the entered value is stored in temp.
The step-by-step working of the while loop (when num and temp both contains 132) is shown in the table given below:
numtemp!=0rem=temp%10;remtot=tot+rem;tottemp=temp/10;tempComment
132----0-132Initial Values
132132!=0
↓
True
rem=132%10;2tot=0+2;2temp=132/10;13Iteration 1
13213!=0
↓
True
rem=13%10;3tot=2+3;5temp=13/10;1Iteration 2
1321!=0
↓
True
rem=1%10;1tot=5+1;6temp=1/10;0Iteration 3
1320!=0
↓
False
------While
loop
stops
working
as
temp!=0
is
evaluated
to
False
While executing the while loop:
  • At first value of temp is checked to see whether it is 0 or not.
  • The condition temp!=0 will produce either True or False after evaluation.
    • If it is True, the statements written within while loop are executed and the loop continues to iterate till the condition is True.
    • If it is False then the statements written within while loop are not executed and the control goes to the statement written immediately after the loop.
  • Within while loop, at first the last digit is extracted from the value stored in temp by performing modulo division operation using the expression temp%10. Thus the expression temp%10 will give the remainder after integer division which is the last digit of the value stored in temp and the result is stored in rem. 

  • After that the value stored in rem is added with the value stored in tot and the result is stored in the same variable i.e. tot. 

  • The value stored in temp is divided by 10 to remove the last digit of the value stored in it and the result is stored in the same variable i.e. temp.

Thus the above process is used to find the sum of the digits present in the given number.

The final result is stored in tot. 

Finally the sum of the digits present in the entered integer value along with the value is displayed on the output screen.

Share this page on
Scroll to Top