Numbers with Even 1s in Binary
Print numbers whose binary form has an even count of ones. Students use Python bin, slicing, count, and a parity test that differs from even-number testing.
1# Print numbers2print("Numbers with even 1s in binary:")3for num in range(1, 21):4 # Count 1s in binary5 binary = bin(num)[2:] # Remove '0b' prefix6 count_ones = binary.count('1')78 if count_ones % 2 == 0:9 print(f"{num} (binary: {binary})", end=" ")10print()
Output
Numbers with even 1s in binary: 3 (binary: 11) 5 (binary: 101) 6 (binary: 110) 9 (binary: 1001) 10 (binary: 1010) 12 (binary: 1100) 15 (binary: 1111) 17 (binary: 10001) 18 (binary: 10010) 20 (binary: 10100)
In this one
- Read binary text
- Count set bits
- Distinguish bit parity from value parity
How it works
- 1
Convert each candidate with bin and remove 0b.
- 2
Count its one characters.
- 3
Print when that count is even.
Edge cases
Does three qualify?
Does three qualify?
Yes. Its binary representation contains two ones.
Does two qualify?
Does two qualify?
No. Binary 10 contains only one one.
What's going on
bin creates binary text with a 0b prefix. The slice [2:] removes that prefix before count('1') counts set bits.
The filter asks whether that count is even, not whether num is even. Three has binary 11, so it qualifies despite being odd. The fixed outer range tests one through twenty and prints each accepted decimal value beside its binary representation.
Does three qualify? Yes. Its binary representation contains two ones.
Does two qualify? No. Binary 10 contains only one one.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does [2:] remove?
Pick an answer to check it.
Question 2
Does three qualify?
Pick an answer to check it.
Questions people ask
Does three qualify?
Yes. Its binary representation contains two ones.
Does two qualify?
No. Binary 10 contains only one one.
What does [2:] remove?
The 0b prefix.
๐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