Digit Sum

Write a Python program that reads a positive integer from the user and prints the sum of its digits.

Example 1:

Input: 1234 
Output: 10

Example 2:

Input: 56789 
Output: 35

You will need to extract each digit from the number to add them together. Consider using a while loop to do this.

n = int(input("Enter a number: "))
total = 0
while n > 0:
    digit = n % 10
    total += digit
    n = n // 10
print("Sum of digits:", total)

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!