Fizz Buzz for multiples of 2 and 3

EasyIf-Else Programs · 31 of 64

Write a Python program that prints “FizzBuzz” for multiples of both 2 and 3, “Fizz” for multiples of 2 and “Buzz” for multiples of 3; otherwise print the number.

Advertisement
Input
14, 9, 6, 7
Output
14 Fizz
9 Buzz
6 FizzBuzz
7 7

Approach

  1. Test the combined case first, then each single case.

Solution

Python
for n in [14, 9, 6, 7]:    if n % 2 == 0 and n % 3 == 0:        print(n, "FizzBuzz")    elif n % 2 == 0:        print(n, "Fizz")    elif n % 3 == 0:        print(n, "Buzz")    else:        print(n, n)
Output
14 Fizz
9 Buzz
6 FizzBuzz
7 7

Line by line

Line 2

Multiples of both must be checked first, otherwise 6 would stop at “Fizz”.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs