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.
1# Take number2num = int(input("Enter a number: "))34# Sum odd and even digits5sum_odd = 06sum_even = 07temp = abs(num)89while temp > 0:10 digit = temp % 1011 if digit % 2 == 0:12 sum_even += digit13 else:14 sum_odd += digit15 temp //= 101617print(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
Extract a digit from abs(num).
- 2
Add it to the even or odd total by parity.
- 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.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum