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.

  1. Take user input

    • The user enters a number, which is stored in num.
  2. Initialize total to store the sum of digits

    • total = 0 starts at zero and accumulates the sum of the digits.
  3. Extract and sum each digit using a while loop

    • digit = num % 10 gets the last digit of num.
    • total = total + digit adds the digit to total.
    • num = num // 10 removes the last digit from num.
  4. Repeat until all digits are processed

    • The loop runs until num becomes zero.
  5. Print the sum of digits

    • After the loop ends, total holds the sum of all digits, which is printed.

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