Python Practice › If-Else Programs › Program 31
Fizz Buzz for multiples of 2 and 3
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.
Input
14, 9, 6, 7
Output
14 Fizz 9 Buzz 6 FizzBuzz 7 7
Approach
- Test the combined case first, then each single case.
Solution
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”.
Learn the concept
New to this topic? Read the lesson, then come back.