In this tutorial, we will write a simple Python program to add the digits of a number using while loop. For example, if the input number is 1234 then the output would be 1+2+3+4 = 10 (sum of digits).
Program to sum all the digits of an input number
In this program user is asked to enter a positive number and the program then adds the digits of that number using while loop.
# Program published on https://beginnersbook.com # Python program to sum all the digits of an input number num = int(input("Enter a Number: ")) result = 0 hold = num # while loop to iterate through all the digits of input number while num > 0: rem = num % 10 result = result + rem num = int(num/10) # displaying output print("Sum of all digits of", hold, "is: ", result)
Output 1:
Enter a Number: 5257 Sum of all digits of 5257 is: 19
Output 2:
Enter a Number: 1200 Sum of all digits of 1200 is: 3
Output 3:
Enter a Number: 1004 Sum of all digits of 1004 is: 5
Related Python Examples:
1. Python program to add subtract multiply and divide two numbers
2. Python program to add two matrices
3. Python program to add two binary numbers
4. Addition of two numbers in Python
Leave a Reply