3. FizzBuzz
Write a function fizzbuzz(n) that takes a whole number n and returns a list of strings, one for each number from
1 to n, in order. For each number, the string is:
"FizzBuzz"if the number is a multiple of both 3 and 5,"Fizz"if it is a multiple of 3 only,"Buzz"if it is a multiple of 5 only,- otherwise the number itself, as a string:
"7", not7.
A multiple of 3 is a number that 3 divides with nothing left over: 3, 6, 9, 12 and so on. If n is 0, return an
empty list [].
Example 1
n = 5["1", "2", "Fizz", "4", "Buzz"]Example 2
n = 15["1", "2", "Fizz", "4", "Buzz", "Fizz", "7",
"8", "Fizz", "Buzz", "11", "Fizz", "13", "14",
"FizzBuzz"]Example 3
n = 1["1"]Constraints
nis a whole number from 0 to 100.
Submit also runs 3 more tests you can't see.
Practises For Loops (lesson 13).
- Loop with
for i in range(1, n + 1):soitakes every value from 1 ton. Whennis 0 the range is empty and you return[]. i % 3 == 0isTruewhen 3 dividesiexactly. Check for both 3 and 5 first (i % 15 == 0), or 15 gets caught by the test for 3 alone.- Append
"FizzBuzz","Fizz"or"Buzz", and otherwisestr(i): every item must be a string, numbers too.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def fizzbuzz(n):
"""Build the FizzBuzz list for the numbers 1 to n.
n: int, how many numbers (0 or more)
Returns: list of str, one string for each number 1..n
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.