Python Program to find sum of digits
Program
num = int(input("Enter a number: "))
total = 0
while(num > 0):
digit = num % 10
total = total + digit
num = num // 10
print("Sum of digits:\t", total)
This program calculates the sum of the digits of a given number using a loop.
-
Take user input
- The user enters a number, which is stored in
num
.
- The user enters a number, which is stored in
-
Initialize
total
to store the sum of digitstotal = 0
starts at zero and accumulates the sum of the digits.
-
Extract and sum each digit using a while loop
digit = num % 10
gets the last digit ofnum
.total = total + digit
adds the digit tototal
.num = num // 10
removes the last digit fromnum
.
-
Repeat until all digits are processed
- The loop runs until
num
becomes zero.
- The loop runs until
-
Print the sum of digits
- After the loop ends,
total
holds the sum of all digits, which is printed.
- After the loop ends,
Key Takeaways
- The program extracts digits one by one and adds them together.
- It efficiently computes the sum without converting the number to a string.
- The approach works for positive integers. If negative numbers need to be handled, modifications are required.
Output
Enter a number: 37294
Sum of digits: 25