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

Sum of Odd & Even Digits Separately

Add odd digits and even digits into separate totals with Python. Students classify each extracted digit by parity rather than by its position in the number.

AdvancedPhase 2 - Level 5: Logical Loop CombinationsExample 9 of 12
sum-of-odd-even-digits-separately.py
1# Take number
2num = int(input("Enter a number: "))
3
4# Sum odd and even digits
5sum_odd = 0
6sum_even = 0
7temp = abs(num)
8
9while temp > 0:
10 digit = temp % 10
11 if digit % 2 == 0:
12 sum_even += digit
13 else:
14 sum_odd += digit
15 temp //= 10
16
17print(f"Sum of odd digits: {sum_odd}")
18print(f"Sum of even digits: {sum_even}")

Output

Enter a number: 12345
Sum of odd digits: 9
Sum of even digits: 6

In this one

  • Classify digits by value
  • Maintain two totals
  • Ignore the sign

How it works

  1. 1

    Extract a digit from abs(num).

  2. 2

    Add it to the even or odd total by parity.

  3. 3

    Remove it and continue until temp is zero.

Edge cases

Where does digit zero go?

Where does digit zero go?

Into the even-digit branch.

What happens for input zero?

What happens for input zero?

Both totals stay zero when the loop is skipped.

What's going on

The code scans abs(num), so a negative sign never enters either sum. Each digit's remainder modulo two decides its destination.

For 1234, odd digits one and three total four; even digits two and four total six. Zero belongs to the even branch but changes its total by zero. The position of a digit does not determine which accumulator receives it.

Where does digit zero go? Into the even-digit branch.

What happens for input zero? Both totals stay zero when the loop is skipped.

Quiz

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

Question 1

Which property chooses a total?

Pick an answer to check it.

Question 2

Where does digit zero go?

Pick an answer to check it.

Questions people ask

Where does digit zero go?

Into the even-digit branch.

What happens for input zero?

Both totals stay zero when the loop is skipped.

Which property chooses a total?

The digit value's parity.