Python Basics · Repeating Work · lesson 12 of 12
Workshop: FizzBuzz
about 15 minutes · free · runs in your browser
Step 1 of 2
The classic
FizzBuzz is the traditional first interview question, and it uses everything in this module at once.
For each number from 1 to n:
- divisible by 3 and 5 →
"FizzBuzz" - divisible by 3 →
"Fizz" - divisible by 5 →
"Buzz" - otherwise → the number itself, as a string
n % 3 == 0 is how you ask "is this divisible by three?".
The trap is ordering. If you test n % 3 first, then 15 comes out as "Fizz" and the
FizzBuzz case never happens. Check the most specific condition first.
Your turn: write fizzbuzz(n) returning the list of strings for 1 to n
inclusive.
You start from this, and edit it in the browser:
def fizzbuzz(n):
# Return the list of FizzBuzz strings for 1 to n.
pass
Step 2 of 2
Printing it
The version you would actually run prints as it goes rather than building a list.
Combine what you know: a loop, a chain of conditions, and print().
Your turn: print the FizzBuzz sequence for 1 to 15, one entry per line. The output
starts 1, 2, Fizz, 4, Buzz and ends with FizzBuzz on the last line.
You start from this, and edit it in the browser:
# Print FizzBuzz for 1 to 15, one per line.