- Python Basic Programs
- Python Program Examples
- Python Print Hello World
- Python Get Input from User
- Python Add Two Numbers
- Add Subtract Multiply Divide
- Python Check Even or Odd
- Python Check Prime or Not
- Python Check Alphabet or Not
- Python Check Vowel or Not
- Python Check Leap Year or Not
- Check Reverse equal Original
- Check Positive Negative Zero
- Python Check Armstrong or Not
- Python Check Palindrome or Not
- Python Check Perfect Number
- Python Find Reverse of Number
- Python Count Digits in Number
- Python Add Digits of Number
- Sum of First and Last Digits
- Python Product of Mid Digits
- Sum of Squares of Digits
- Interchange Digits of Number
- Python Sum of n Numbers
- Python Print ASCII Values
- Python Swap Two Numbers
- Python Swap Two Variables
- Python Fahrenheit to Celsius
- Python Celsius to Fahrenheit
- Python Display Calendar
- Python Days into Years, Weeks
- Find Largest of Two Number
- Find Largest of Three Number
- Python Print Fibonacci Series
- Generate Armstrong Numbers
- Python Make Simple Calculator
- Python Add Binary Numbers
- Binary Number Multiplication
- Python Mathematical Programs
- Find Sum of Natural Numbers
- Find Average of n Numbers
- Python Print Multiplication Table
- Print Table using Recursion
- Python Find Average Percentage
- Python Find Grade of Student
- Find Square Root of Number
- Python Print Prime Numbers
- Find Numbers Divisible by
- Python Find Factors of Number
- Python Find Factorial of a Number
- Python Find HCF & LCM
- Python Kilometres to Miles
- Python Find Area of Square
- Python Find Area of Rectangle
- Python Find Area of Triangle
- Python Find Area of Circle
- Python Find Perimeter of Square
- Find Perimeter of Rectangle
- Python Find Perimeter of Triangle
- Find Circumference of Circle
- Python Simple Interest
- Python Solve Quadratic Equation
- Python Different Set of Operations
- Python Display Powers of 2
- Python Find nCr & nPr
- Python Pattern Programs
- Python Print Pattern Programs
- Python Print Diamond Pattern
- Python Print Floyd's Triangle
- Python Print Pascal's Triangle
- Python List Programs
- Python Count Even/Odd in List
- Python Positive/Negative in List
- Python Even Numbers in List
- Python Odd Numbers in List
- Python Sum of Elements in List
- Sum of Odd/Even Numbers
- Python Element at Even Position
- Python Element at Odd Position
- Python Search Element in List
- Python Largest Number in List
- Python Smallest Number in List
- Python Second Largest in List
- Python Second Smallest in List
- Python Insert Element in List
- Python Delete Element from List
- Python Multiply Numbers in List
- Swap Two Elements in List
- Python 1D Array Program
- Python Linear Search
- Python Binary Search
- Python Insertion Sort
- Python Bubble Sort
- Python Selection Sort
- Remove Duplicates from List
- Python Reverse a List
- Python Merge Two List
- Python Copy a List
- Python Conversion Programs
- Python Decimal to Binary
- Python Decimal to Octal
- Python Decimal to Hexadecimal
- Python Binary to Decimal
- Python Binary to Octal
- Python Binary to Hexadecimal
- Python Octal to Decimal
- Python Octal to Binary
- Python Octal to Hexadecimal
- Python Hexadecimal to Decimal
- Python Hexadecimal to Binary
- Python Hexadecimal to Octal
- Python Matrix Programs
- Python Add Two Matrices
- Python Subtract Two Matrices
- Python Transpose Matrix
- Python Multiply Matrices
- Python String Programs
- Python Print String
- Python Find Length of String
- Python Compare Two Strings
- Python Copy String
- Python Concatenate String
- Python Reverse a String
- Python Swap Two Strings
- Python Uppercase to Lowercase
- Python Lowercase to Uppercase
- Python Check Substring in String
- Python Count Character in String
- Count Repeated Characters
- Python Count Word in Sentence
- Python Count Each Vowels
- Python Capitalize Character
- Python Capitalize Word in String
- Python Smallest/Largest Word
- Remove Spaces from String
- Remove Duplicate Character
- Remove Vowels from String
- Remove Punctuation from String
- Python Remove Word in String
- Python Remove Duplicate Words
- WhiteSpace to Hyphens
- Replace Vowels with Character
- Replace Character in String
- Python Sort String in Alphabetical
- Sort Word in Alphabetical Order
- Extract Number from String
- Python Check Anagram Strings
- Python File Programs
- Python Read a File
- Python Write to File
- Python Append Text to File
- Python Copy Files
- Python Merge Two Files
- Python Counts Characters in File
- Python Count Words in File
- Python File Content in Reverse
- Python Lines Contains String
- Python Delete Line from File
- Python Capitalize Word in File
- Python Replace Text in File
- Replace Specific Line in File
- Python Find Size of File
- Python List Files in Directory
- Python Delete Files
- Python Misc Programs
- Python Reverse a Tuple
- Python Merge Two Dictionary
- Python bytes to String
- Python bytearray to String
- Generate Random Numbers
- Python Print Address of Variable
- Python Print Date and Time
- Python Get IP Address
- Python Shutdown/Restart PC
- Python Tutorial
- Python Tutorial
Python Program to Add Digits of a Number
In this article, you will learn and get code in Python, to find and print the sum of digits of a number entered by user at run-time. Here are the list of approaches used to do the task:
- Add Digits of a Number using while Loop
- Using for Loop
- Using Function
- Using class
For example, if user enters a number say 235, then the output will be 2+3+5, that is 10.
Add Digits of a Number using while Loop
The program given below receives a number as input from user, and uses a while loop to find the sum of digits of given number:
print("Enter a Number") num = int(input()) sum = 0 while num>0: rem = num%10 sum = sum+rem num = int(num/10) print("\nSum of Digits of Given Number: ", sum)
Here is the initial output produced by this Python program:
Now supply the input say 123 and press ENTER
key to find and print the summation of its digit
1, 2, and 3 as shown in the snapshot given below:
The dry run of above program with user input 123 goes like:
- Since user enters 123, then it gets stored in num. Therefore num=123 (entered by user) and sum=0 (initialized 0 as its initial value)
- Now the condition of while loop gets evaluated. That is, the condition num>0 or 123>0 evaluates to be true, therefore program flow goes to its body and evaluates all the three statements
- So num%10 or 123%10 or 3 gets initialized to rem. Now rem=3
- And sum+rem or 0+3 or 3 gets initialized to sum. Now sum=3
- And finally int(num/10) or int(123/10) or int(12.3) or 12 gets initialized as new value of num. Now num=12
- Now the condition of while loop again gets evaluated. Because this time also the condition num>0 or 12>0 evaluates to be true, therefore again, all three statements gets executed. This process continues until the condition evaluates to be false
- In this way, after exiting from the loop, we'll have a variable named sum that holds 6, the sum of digits of given number
- Therefore just print the value of sum as output
Modified Version of Previous Program
This is the modified version of previous program. In this program, if user enters a number say 124, then output looks like 1+2+4=7
print(end="Enter a Number: ") num = int(input()) sum = 0 print(end="\n") while num>0: rem = num%10 sum = sum+rem num = int(num/10) if num==0: print(end=str(rem)) else: print(end=str(rem)+ "+") print(" = " +str(sum))
Here is its sample run with user input, 130259:
Note - The end is used to skip adding an automatic newline using print().
Add Digits of Number using for Loop
Now this program uses for loop instead of while to do the same task, that is to find and print the sum of given number's digits.
print("Enter a Number: ", end="") num = int(input()) sum = 0 temp = num for i in range(len(str(temp)), 0, -1): rem = num%10 sum = sum+rem num = int(num/10) print("\nSum of Digits of " +str(temp)+ " = " +str(sum))
Here is its sample run with user input, 4052:
Note - The third parameter of for loop (-1) is used to loop with loop variable (i) in reverse order. That is, the size of given number to 1 (one greater than 0 (the second parameter))
Since the length of "4052" (a string) is 4, therefore all three statements gets executed three times.
Note - The str() is used to convert an int value to a string type value
Note - The len() is used to find the length of string.
Add Digits of Number using Function
This program uses a user-defined function named addNumDig() to find the sum of digits of a given number. The function receives a number as its argument and returns the sum of its digit.
def addNumDig(n): sum = 0 while n>0: rem = n%10 sum = sum+rem n = int(n/10) return sum print("Enter a Number: ", end="") num = int(input()) res = addNumDig(num) print("\nSum of Digits of " +str(num)+ " = " +str(res))
This program produces the same output as of previous program.
Add Digits of Number using Class
This is the last program of this article. The program is created using class and object, an object-oriented feature of Python.
class fresherearth: def addNumDig(self, n): sum = 0 while n>0: rem = n%10 sum = sum+rem n = int(n/10) return sum print("Enter a Number: ", end="") num = int(input()) ccObj = fresherearth() res = ccObj.addNumDig(num) print("\nSum of Digits of " +str(num)+ " = " +str(res))
Here is its sample run with user input, 1046:
Using the following statement:
ccObj = fresherearth()
All properties of the class named fresherearth gets assigned to an object named ccObj. Now this object can be used to access the member function of class fresherearth using dot (.) operator.
Same Program in Other Languages
« Previous Program Next Program »