Home › Learn › Python › Loops

FizzBuzz

Lesson 15 of 40. The classic loop-and-conditions exercise, done properly.

FizzBuzz asks for the numbers from 1 to n, except that multiples of 3 become Fizz, multiples of 5 become Buzz, and multiples of both become FizzBuzz. It combines everything so far: a range, a chain of conditions, and building a list.

The trap is the order of the checks. If you test "multiple of 3" first, 15 becomes Fizz and never gets a chance at FizzBuzz. Test the most specific condition (both) first, or build the word from two independent checks and fall back to the number when the word is empty.

Your task

Write fizzbuzz(n) that returns a list of strings for 1 to n: "Fizz", "Buzz", "FizzBuzz", or the number as a string, so fizzbuzz(5) is ["1", "2", "Fizz", "4", "Buzz"].

Hint 1

Check i % 15 == 0 first (a multiple of both 3 and 5).

Hint 2

str(i) turns the number into text.

Show the solution
def fizzbuzz(n):
    result = []
    for i in range(1, n + 1):
        if i % 15 == 0:
            result.append("FizzBuzz")
        elif i % 3 == 0:
            result.append("Fizz")
        elif i % 5 == 0:
            result.append("Buzz")
        else:
            result.append(str(i))
    return result

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.