Sum of Digit of a Number Without Recursion in Python

This is a Python Program to find the sum of digits in a number without using recursion.

Problem Description

The program takes a number and finds the sum of digits without using recursion.

Problem Solution

1. Take a number from the user.
2. Using a while loop, obtain each digit and append it to the list.
3. Use the sum() function to obtain the sum of digits in the list.
4. Exit.

Program/Source Code

Here is source code of the Python Program to find the sum of digits in a number without using recursion. The program output is also shown below.

l=[]
b=int(input("Enter a number: "))
while(b>0):
    dig=b%10
    l.append(dig)
    b=b//10
print("Sum is:")
print(sum(l))
Program Explanation

1. User must enter a number.
3. The condition for the while loop is that the number should be greater than 0.
4. Otherwise, each digit is obtain and appended to the list.
5. The sum of elements in the list is obtained using the sum() function and printed which is the sum of digits of the number.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter a number: 123
Sum is:
6
 
Case 2:
Enter a number: 567
Sum is:
18

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.