Zed-King Institute

    Python Program to Find the Sum of Digits of a Number

    easywhile loopPython

    The standard way to take a number apart digit by digit — the same technique is used for reverse, palindrome and Armstrong programs.

    The question

    Read a positive integer and print the sum of its digits. Use a while loop with % 10 and // 10.

    The code

    program.py

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

    Input

    72050

    Output

    Sum of digits = 14

    How it works

    1. 1n % 10 gives the last digit (1234 % 10 = 4).
    2. 2Add that digit to total.
    3. 3n //= 10 removes the last digit (1234 becomes 123).
    4. 4Repeat while n is greater than 0; when every digit is used, n becomes 0 and the loop ends.

    Common mistakes

    • Using / instead of // — n becomes 123.4 and the loop never works properly.
    • Forgetting to change n inside the loop, which makes the loop run forever.

    Now solve a similar question yourself

    A new Python question every time, checked instantly.

    Practice questions

    More in while loop