FizzBuzz
The classic programming interview question that tests loops and conditionals
FizzBuzz is perhaps the most famous programming interview question. It has become a standard test for basic programming competency because it requires understanding of loops, conditional statements, and the modulo operator.
๐ Concepts & Theory
FizzBuzz tests your understanding of several core programming concepts working together:
The Modulo Operator (%)
Returns the remainder after division:
10 % 3 # Returns 1 (10 รท 3 = 3 remainder 1)
15 % 5 # Returns 0 (15 รท 5 = 3 remainder 0)
15 % 3 # Returns 0 (15 รท 3 = 5 remainder 0)
If n % x == 0, then n is divisible by x.
The range() Function
Generates a sequence of numbers:
range(1, 21) # 1 to 20 (end is exclusive)
range(5) # 0 to 4
range(0, 10, 2) # 0, 2, 4, 6, 8 (step of 2)
Condition Order Matters!
The key insight is checking for divisibility by BOTH 3 AND 5 first:
if n % 3 == 0 and n % 5 == 0: # Check this FIRST
print("FizzBuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)
If you check for 3 first, numbers like 15 would print "Fizz" instead of "FizzBuzz".
Alternative: Check 15 Directly
Since any number divisible by both 3 and 5 must be divisible by 15 (their LCM):
if n % 15 == 0:
print("FizzBuzz") ๐ฏ Your Challenge
Write a program that prints numbers from 1 to 20. For multiples of 3, print "Fizz". For multiples of 5, print "Buzz". For multiples of both, print "FizzBuzz".
๐ Starter Code
for i in range(1, 21):
# Your logic here
pass
- Use the modulo operator (%) to check divisibility
- Check for divisibility by BOTH 3 AND 5 first
- Numbers divisible by both 3 and 5 are also divisible by 15
- range(1, 21) gives you 1 through 20
Solution
for i in range(1, 21):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
Explanation
This solution iterates through 1-20, checking divisibility in the correct order: first both 3 AND 5, then just 3, then just 5. The key is checking the combined condition first.
โ ๏ธ Common Mistakes to Avoid
- Checking for 3 or 5 before checking for both
- Using range(20) which starts at 0
- Using = instead of == for comparison
- Forgetting the colon after if/elif/else