STEM

Python teaser/puzzle: FizzBuzz Twister

Objective

For numbers 1 through 20, print “Fizz” if the number is divisible by 3 (no need to print the number), “Buzz” if it’s divisible by 5 (no need to print the number), and “FizzBuzz” if it’s divisible by both (no need to print the number). Otherwise, just print the number.

For example, for numbers 1 to 5, the output would look like this:

1
2
Fizz
(because 3 is divisible by 3)
4
Buzz
(because 5 is divisible by 5)

If the range was up to 20, you should get only one instance of “FizzBuzz” since only 15 is divisible by both 3 and 5.

Implement in 3 different ways:

  1. Using if-else
  2. Using match-case
  3. Without using else,elif, or match-case (use only if).

Hints

Think Modulus operator for full divisibility.
For implementing #3, build up a string as you go along each test.

Click Run on the widget below to run the solution. All three methods are implemented in this script and their outputs are shown one after another separated by dashed lines.

Solution

Try to solve it yourself first. If you’re stumped, click here for the solution. Code will be revealed. You can also edit the code and run your edits in real-time. Try changing the upper limit to another number from 20, run it and see for yourself.

For more brain teasers and puzzles, click here.

Fun Facts

The term ‘Fizz buzz’ comes from word game for children to teach them about division, usually played as a group. Players take turns to count replacing any number divisible by three with the word ‘fizz’, and any number divisible by five with the word ‘buzz’. Fizz buzz had also become a teaser for programmers and has been implemented in many languages over time. It still remains a classic teaser, and some programmers even occasionally encounter them in entry level interviews.

Back To Top