Hi Programmers, Here is the article to find sum of digits of numbers using python programming. That's important program for python beginners. Let's see the code.
Code Explanation :
Sum = 0 :- First i initialize sum integer variable with 0.
n1 = int(input("Enter Any Positive Number : ")) :- Enter Any Positive Number : that display output screen. now enter value
accept into string then due to typecasting that convert into integer.
while n1 != 0 :- now control transfer to while loop, if condition true then while loop continue.
sum = sum + n1 % 10 :- sum = 0 if user enter 345. 345%10=5, then 0+5 =5
n1 = int (n1 / 10 ) :- 345 / 10 = 34. and due to typecasting decimal values convert into integer.
print(" Sum of Digits of Number = ",sum) :- when while loop exit then print "Sum of Digits of Number =" and value of sum
into output screen.
Code Explanation :
Sum = 0 :- First i initialize sum integer variable with 0.
n1 = int(input("Enter Any Positive Number : ")) :- Enter Any Positive Number : that display output screen. now enter value
accept into string then due to typecasting that convert into integer.
while n1 != 0 :- now control transfer to while loop, if condition true then while loop continue.
sum = sum + n1 % 10 :- sum = 0 if user enter 345. 345%10=5, then 0+5 =5
n1 = int (n1 / 10 ) :- 345 / 10 = 34. and due to typecasting decimal values convert into integer.
print(" Sum of Digits of Number = ",sum) :- when while loop exit then print "Sum of Digits of Number =" and value of sum
into output screen.
Happy Coding...Thanks.
ConversionConversion EmoticonEmoticon