FizzBuzz is the most famous beginner coding challenge, and it even shows up in job interviews. It mixes a loop, if/elif and the % operator. Let's solve it step by step.
THE RULES
Count from 1 to 15. For each number:
- if it divides by 3, print Fizz
- if it divides by 5, print Buzz
- if it divides by both 3 and 5, print FizzBuzz
- otherwise, print the number
STEP 1: "DIVIDES BY" MEANS % IS 0
% gives the remainder of a division. If the remainder is 0, the number divides evenly.
print(9 % 3)
print(10 % 3)0
1
STEP 2: LOOP FROM 1 TO 15
range(1, 16) gives 1 to 15, because the end number is never included.
STEP 3: THE FULL SOLUTION
for n in range(1, 16):
if n % 15 == 0:
print("FizzBuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
% 15) first. If you check % 3 first, 15 would print "Fizz" and the elif chain would stop there.n = 30
if n % 3 == 0:
print("Fizz")
elif n % 15 == 0:
print("FizzBuzz")
else:
print(n)% 15 check is never reached.ANOTHER WAY: BUILD THE WORD
Start with empty text and add pieces. If nothing was added, use the number.
for n in range(9, 16):
word = ""
if n % 3 == 0:
word += "Fizz"
if n % 5 == 0:
word += "Buzz"
print(word or n)Fizz
Buzz
11
Fizz
13
14
FizzBuzz
word or n uses word if it is not empty, otherwise n. Here the two ifs are separate on purpose, so 15 gets both pieces.
COMMON BEGINNER MISTAKES
if/elif chain. FizzBuzz never prints.range(1, 15). That stops at 14. Use range(1, 16)./ instead of %. 9 / 3 is 3.0, not the remainder.PRACTICE IT, DON'T JUST READ IT
FizzBuzz is the boss of Loop Lagoon in Snekcade. Beat it on your phone with hints if you get stuck. It is free.
PLAY LOOP LAGOON ▸FAQ
What is FizzBuzz?
A small programming challenge: count from 1 to a number, printing Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for multiples of both.
Why is my FizzBuzz never printing FizzBuzz?
You probably check % 3 before % 15 in an if/elif chain. Check the "both" case first.
What does % mean in Python?
It is the remainder operator: 10 % 3 is 1. If n % 3 == 0, n divides evenly by 3.