FizzBuzz is a classic interview warm-up. Count from 1 upwards. For multiples of 3 print Fizz, for multiples of 5 print Buzz, for multiples of both print FizzBuzz, and for every other number print the number.
The program
python
for i in range(1, 16): if i % 15 == 0: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(i)
output
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
How it works
i % 3 == 0is true whenidivides by 3 with no remainder.- A number divisible by both 3 and 5 is divisible by 15, so
i % 15 == 0checks "both" in one test. - The order of the checks matters.
if/elifstops at the first true condition. If the% 3check came first, 15 would printFizzand never reach the FizzBuzz line. range(1, 16)gives 1 to 15. The end number is not included. Change it torange(1, 101)for the usual 1 to 100.
Another way: build the word
This version adds Fizz and Buzz to a string, so it needs no separate check for 15. It is also easier to extend: a third rule (here, Bazz for multiples of 7) is one more line.
python
for i in range(1, 22): word = "" if i % 3 == 0: word += "Fizz" if i % 5 == 0: word += "Buzz" if i % 7 == 0: word += "Bazz" print(word or i)
output
1 2 Fizz 4 Buzz Fizz Bazz 8 Fizz Buzz 11 Fizz 13 Bazz FizzBuzz 16 17 Fizz 19 Buzz FizzBazz
word or i gives word if it is not empty, and i otherwise. An empty string counts as false in Python.