PythonMastery

FizzBuzz program in Python

Print the numbers 1 to 15, but Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for multiples of both. Why the order of the checks matters.

FizzBuzz is a classic interview warm-up. Count from 1 upwards. For multiples of 3 print Fizz, for multiples of 5 print Buzz, for multiples of both print FizzBuzz, and for every other number print the number.

The program

python
for i in range(1, 16):
    if i % 15 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)
output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

How it works

Another way: build the word

This version adds Fizz and Buzz to a string, so it needs no separate check for 15. It is also easier to extend: a third rule (here, Bazz for multiples of 7) is one more line.

python
for i in range(1, 22):
    word = ""
    if i % 3 == 0:
        word += "Fizz"
    if i % 5 == 0:
        word += "Buzz"
    if i % 7 == 0:
        word += "Bazz"
    print(word or i)
output
1
2
Fizz
4
Buzz
Fizz
Bazz
8
Fizz
Buzz
11
Fizz
13
Bazz
FizzBuzz
16
17
Fizz
19
Buzz
FizzBazz

word or i gives word if it is not empty, and i otherwise. An empty string counts as false in Python.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Control Flow: Conditionals, Operators & Expressions