Program to find sum of digits in python using for loop. This Python program first takes the number as input. After that sum the digits in a function and print the sum. This python program with source code is discussed in this post. This python project is useful for beginners and CBSE KV School Class 11 and Class 12 students computer science practical file and NIELIT O Level module.
Write a Program to find sum of digits in python.
How to Proceed
Use function DigitSum() that takes a number and returns its digit sum
Python code of program
Explanation of Source code in program
def DigitSum(n): # Initializing a function name DigitSum with n as the input(n is a number coming from input)
s=0 #takes the initial value as s=0.(sum)
n=str(n) #number is changed to string so that it can be summed
for i in n: # for loop from i to the next n
s=s+int(i) #The numbers are added one by one
return s #the total sum value is returned to the caller
n=int(input(“Enter the number”)) #input here
print(“Sum of digits =”,DigitSum(n)) #print the output here ,program is also called here
Output of the Program
Testing the sum of digits
Type any numbers and press enter. The sum of digits is displayed.
Here in the window the digit of numbers is added . Above we have input 896 whose sum 8+9+6=23 comes out of the program.
Our Program to find sum of digits in python is giving the good result.
Thanks for reading. Visit again.
Source code for sum of digits in Python -> click here
for more python programs -> click here