Python Practice › Loop Programs › Program 7
FizzBuzz from 1 to 30
Write a Python program that prints 1 to 30, but “Fizz” for multiples of 3, “Buzz” for multiples of 5 and “FizzBuzz” for multiples of both.
Output
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz
Approach
- Check the multiple-of-15 case first.
Solution
for n in range(1, 31): if n % 15 == 0: print("FizzBuzz", end=" ") elif n % 3 == 0: print("Fizz", end=" ") elif n % 5 == 0: print("Buzz", end=" ") else: print(n, end=" ")print()Output
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz
Line by line
Line 2
A multiple of both 3 and 5 is a multiple of 15; testing it first stops 15 from printing only “Fizz”.
Learn the concept
New to this topic? Read the lesson, then come back.