Numbers with Even Digit Sum
Filter one through one hundred by an even digit sum with Python. Students combine an outer candidate loop, an inner digit loop, and a final remainder test.
1# Print numbers with even digit sum2print("Numbers 1-100 with even digit sum:")3for num in range(1, 101):4 # Calculate digit sum5 digit_sum = 06 temp = num7 while temp > 0:8 digit_sum += temp % 109 temp //= 101011 # Check if sum is even12 if digit_sum % 2 == 0:13 print(num, end=" ")14print()
Output
...
The sample abbreviates a longer result. The program prints the intervening values; it does not print these dots.
In this one
- Nest a digit scan
- Reset per-candidate state
- Filter a derived total
How it works
- 1
Visit candidates one through one hundred.
- 2
Sum each candidate's digits in its own while loop.
- 3
Print only candidates with an even completed sum.
Edge cases
Does 11 print?
Does 11 print?
Yes. Its digit sum is two.
Does 10 print?
Does 10 print?
No. Its digit sum is one.
What's going on
Each candidate gets a fresh digit_sum and a disposable temp copy. The inner while adds all decimal digits before the candidate is classified.
The parity test applies to the digit sum, not directly to the candidate. For 11, the sum is two, so it prints even though 11 is odd. Resetting the total inside the outer loop keeps candidates independent.
Does 11 print? Yes. Its digit sum is two.
Does 10 print? No. Its digit sum is one.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why reset digit_sum for each candidate?
Pick an answer to check it.
Question 2
Does 11 print?
Pick an answer to check it.
Questions people ask
Does 11 print?
Yes. Its digit sum is two.
Does 10 print?
No. Its digit sum is one.
Why reset digit_sum for each candidate?
Each number needs its own sum.
๐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