← Practice
πŸ“– Functionsfunctions-fizzbuzz
LessonΒ·difficulty 1/5Β·~10 min

Functions: FizzBuzz

Functions: FizzBuzz

A function packages a piece of logic so you can name it and reuse it:

python
def greet(name):
    return "Hello, " + name

greet("Ada")   # "Hello, Ada"

def starts the definition, the name is greet, name is a parameter, and return hands a value back to whoever called the function.

FizzBuzz is the most famous warm-up problem in programming. The rules:

  • multiples of 3 β†’ "Fizz"
  • multiples of 5 β†’ "Buzz"
  • multiples of both 3 and 5 β†’ "FizzBuzz"
  • everything else β†’ the number itself, as a string

Your task

Write a function fizzbuzz(n) that returns a list of strings for the numbers 1 through n (inclusive), applying the rules above.

python
fizzbuzz(5)    # ["1", "2", "Fizz", "4", "Buzz"]
fizzbuzz(0)    # []

Hint: check the both-case (i % 15 == 0) first, then 3, then 5, else the number. str(i) turns a number into its text form.

Tests

  • 1..5
  • empty (n=0)
  • just Fizz
  • reaches FizzBuzz
  • n=16 length (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.