Learn Python · lesson 24 of 60 · about 9 minutes
Project: FizzBuzz
Give Sam a game for a break: check the number first, then build one line with a loop, remainders and an if / elif chain.
What you'll learn
- Read a problem carefully
- Order conditions correctly
- Combine loops and decisions
A game for a break
After all that planning, Sam deserves a break. The assistant gets a small game: Sam types how far to count, from 1 to 30, and it prints every number on one line, with Fizz for a multiple of 3, Buzz for a multiple of 5 and FizzBuzz for both: 1 2 Fizz 4 Buzz. It's the classic interview puzzle, FizzBuzz, and it uses everything from this chapter: a check on what was typed, a loop, decisions in the right order, and a string built up pass by pass.
The challenge
For the numbers 1 to 15:
- multiples of both 3 and 5 print FizzBuzz
- multiples of 3 print Fizz
- multiples of 5 print Buzz
- everything else prints the number
It's a famous interview question because the order of the checks matters. Check "both" first, or 15 will stop at Fizz.
FizzBuzz
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)Output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzzTip
n % 15 == 0 works because a number divisible by both 3 and 5 is divisible by 15. n % 3 == 0 and n % 5 == 0 says the same thing.
Check the number first
Before counting, the assistant checks what Sam typed. not answer.isdigit() or int(answer) < 1 or int(answer) > 30 is safe even for a word like ten: or stops at the first part that's True, so int() never sees text that isn't a number. Each word goes into the line with a space after it, and strip() removes the last space before printing.
The game in the assistant
answer = input("Count to? ").strip()
if not answer.isdigit() or int(answer) < 1 or int(answer) > 30:
print("Pick a number from 1 to 30")
else:
line = ""
for n in range(1, int(answer) + 1):
if n % 15 == 0:
line += "FizzBuzz "
elif n % 3 == 0:
line += "Fizz "
elif n % 5 == 0:
line += "Buzz "
else:
line += f"{n} "
print(line.strip())
Output
Count to? 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzzNow try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.