Beginner Python Exercises

Sum the Digits of a Number

Converting a number to text makes each digit easy to traverse.

What is Sum the Digits of a Number?

Converting a number to text makes each digit easy to traverse.

Add every decimal digit in an integer.

When should you use it?

  • Learn Python syntax through a practical example.
  • Build a foundation for larger programming problems.
  • Test an idea quickly without a local setup.

Example code

Run code →
main.py
number = 12345
# Convert each digit character back to an integer.
total = sum(int(digit) for digit in str(abs(number)))
print(f"sum={total}")

Expected output

sum=15

How it works

int converts each character back to its numeric value before sum combines them.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in Python IDE →