Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Sum of Digits

Add the decimal digits of an integer with Python modulo and floor division. Students follow a running total, a shrinking copy, and sign-independent digit sums.

IntermediatePhase 2 - Level 2: Number-based Looping LogicExample 4 of 14
sum-of-digits.py
1# Take number
2num = int(input("Enter a number: "))
3
4# Sum of digits
5digit_sum = 0
6temp = abs(num)
7
8while temp > 0:
9 digit = temp % 10
10 digit_sum += digit
11 temp //= 10
12
13print(f"Sum of digits: {digit_sum}")

Output

Enter a number: 1234
Sum of digits: 10

In this one

  • Sum digit values
  • Use floor division
  • Preserve the source input

How it works

  1. 1

    Initialize a total and absolute working copy.

  2. 2

    Add temp % 10, then remove that digit.

  3. 3

    Continue to zero and print digit_sum.

Edge cases

What happens for zero?

What happens for zero?

The loop is empty and the total correctly remains zero.

Does -409 produce a negative sum?

Does -409 produce a negative sum?

No. abs makes the digit scan sign-independent.

What's going on

digit_sum starts at zero and temp stores the absolute input. Each iteration adds the current units digit before removing it from temp.

For 409, the digits arrive as nine, zero, and four, giving thirteen. Their extraction order does not affect addition. The source number remains in num, so digit processing does not destroy the value originally entered.

What happens for zero? The loop is empty and the total correctly remains zero.

Does -409 produce a negative sum? No. abs makes the digit scan sign-independent.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is extracted by temp % 10?

Pick an answer to check it.

Question 2

What happens for zero?

Pick an answer to check it.

Questions people ask

What happens for zero?

The loop is empty and the total correctly remains zero.

Does -409 produce a negative sum?

No. abs makes the digit scan sign-independent.

What is extracted by temp % 10?

The current units digit.