Fizz Buzz

Fizz Buzz is a primary school game for children, that aims to help them practice doing simple division quickly in their head. In the game players sit in a circle and take turns counting from one until the game ends. Each time a player’s number is divisible by three though, they must shout “FIZZ”, and each time it is divisible by five they must shout “BUZZ”. If the number is divisible by both three and five they must shout “FIZZ BUZZ”. If at any point someone shouts the wrong thing, they are out of the game – no second chances!

Fizz Buzz game

Programming Fizz Buzz

Whilst primary school teachers love to make math fun and should be applauded, programming interviewers love to ruin all that fun with contrived problems. One of their favourite tricks is to make you code Fizz Buzz as a one player game. Only if you lose this game, you don’t get the job!

Typically this interview question is asked something similar to:

Write a program that prints the numbers from 1 to 100. If a number is a multiple of three print “Fizz” instead of the number, or If a number is a multiple of five “Buzz”. If a number is a multiple of both three > and five print “FizzBuzz”.

A typical first solution to this problem might look something like the following code snippet:

for n in range(1, 16):
    if n % 3 == 0 and n % 5 == 0:
    elif n % 3 == 0:
    elif n % 5 == 0:

Getting to this solution is a good first step, and one which many people struggle with under the pressure of an interview. Common mistakes include forgetting that range has an inclusive lower bound but an exclusive upper one, and muddling up the order of the conditions. This solution could definitely be improved a bit though.

What next?

The solution shown is functionally correct, but can be improved in several ways.

  • Extensibility: What if we wanted to play Fizz Buzz with numbers other than 3 and 5? Currently the solution would require rewriting, which in a real program would mean updating many tests, documentation, etc…

  • Performance: What if we wanted our program to be as performant as possible? The above solution can be optimised in many ways to make it faster to run.

  • Readability: Chaining many if-elif-else together is an easy first approach, but it is most definitely not the most readable. This can be cleaned up using conditional string formatting in recent versions of python.