Calculate the Sum of its Digits in Python


If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits. ( Hint: Use the modulus operator '%')

The program is a simple Python script that takes an input of a five-digit integer from the user and finds the sum of its digits. The program uses a combination of the modulus operator and integer division operator to separate the digits of the input number and add them together.

The program starts by prompting the user to input a five-digit number using the input() function, which is then assigned to the variable "num" and converted to an integer using the int() function.

Then the program uses a variable "sum" to store the sum of the digits and starts a loop to extract each digit of the number by using the modulus operator(%) and integer division operator(//) one by one and adding it to the sum variable. Finally, the program uses the print() function to output the result, which is the sum of the digits in the input number.


Source Code

num=int(input("Enter the five digits Number :"))
sum=0
a=num%10
n=num//10
sum=sum+a
 
a=n%10
n=n//10
sum=sum+a
 
a=n%10
n=n//10
sum=sum+a
 
a=n%10
n=n//10
sum=sum+a
 
a=n%10
sum=sum+a;
print("sum of the Digits = ",sum)

Output

Enter the five digits Number :23754
sum of the Digits =  21


Example Programs