Numbers with Even 1s in Binary

Print numbers whose binary form has even number of 1s.

AdvancedPhase 2 - Level 5: Logical Loop CombinationsExample 6 of 12
numbers-with-even-1s-in-binary.py
1# Print numbers
2print("Numbers with even 1s in binary:")
3for num in range(1, 21):
4 # Count 1s in binary
5 binary = bin(num)[2:] # Remove '0b' prefix
6 count_ones = binary.count('1')
7
8 if count_ones % 2 == 0:
9 print(f"{num} (binary: {binary})", end=" ")
10print()

Output

Numbers with even 1s in binary:
1 (binary: 1) 2 (binary: 10) 4 (binary: 100) ...

What's going on

Convert to binary and count 1s.

Key Concepts:

Use bin() to convert to binary
Count occurrences of '1'
Check if count is even