To add or sum all the digits of a number given by the user in python, first ask from user to enter the number, then break the given number into its digit and sum or add all the digit. Finally display the addition result of the digits of given number.
Following python program ask from the user to enter a number to find the sum of the digit of that number, then display the result as the output in python:
# Python Program - Add Digits of a Number print("Enter 'x' for exit."); num = input("Enter any number: "); if num == 'x': exit(); try: number = int(num); except ValueError: print("Kindly try to enter a number..exiting.."); else: sum = 0; temp = number; while number > 0: rem = number % 10; sum += rem; number //= 10; print("Sum of all digits of", temp, "is", sum);
Here is the snapshot of sample run of above python program:
This is the sample output produced just after running the above program asking from user to enter any number to sum all the digits of supplied number:
Let's type any number say 123 to see what the above program will print after pressing the enter key. As the program is created to find the sum of all the digits of any number. Therefore here in this case, the number is 123, then its digits will be 1, 2 and 3 and sum of these digits will be 1+2+3 which will be 6.
Here is the same program written and run on python shell:
You may also like to learn or practice the same program in other popular programming languages: