What is the Fizz-Buzz test?

It’s a programming interview question designed to filter out candidates who can’t program.

Problem statement : Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Out of curiousity, I decided to solve this problem.

My first attempt :

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

Output after running python3 can be found here.

The above code can be improved by removing redundant checking of divisibility by 3 and 5. Also important to note that FizzBuzz = Fizz + Buzz.

Improved version :

for ix in range(1,101):
    res = ''
    if ix%3 == 0:
        res += 'Fizz'
    if ix%5 == 0:
        res += "Buzz"
    print(res or ix)

Let me explain the print(res or ix) part : the or operator is a short circuit operator, so res is printed if it is not empty (it’s either a multiple of 3, 5 or both), otherwise ix is printed.

Links :