Skip to content
Ayotl

← All challenges

Basic · easy · loop, modulo

FizzBuzz

The challenge

Print the numbers from 1 to N. For multiples of 3 print Fizz instead of the number, for multiples of 5 print Buzz, and for multiples of both print FizzBuzz.

Example (N = 15)

1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

Idea: check the "both" case first (15 divides) or build the word by appending Fizz and Buzz separately and print the number if it is empty.

The solution

# FizzBuzz - ayotl.dev
def fizzbuzz(n):
    for i in range(1, n + 1):
        word = ""
        # build the word: 15 gets both
        if i % 3 == 0:
            word += "Fizz"
        if i % 5 == 0:
            word += "Buzz"
        # no word? print the number
        print(word or i, end=" ")
    print()


fizzbuzz(15)

$ python3 fizzbuzz.py

1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

The video

Watch on YouTube →