Fizz Buzz implementation in Python
Problem
Write a program that prints numbers from 1 to 100, and:
- For multiples of
3, printFizzinstead of the number. - For multiples of
5, printBuzz. - For multiples of
3and5, printFizzBuzz. - For others, print
number.
Example
Input
1,2,3,4,5... 100
Output
1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14,
FizzBuzz…
Explanation
-
1and2are not multiples of either3or5, so we print the same number. -
3is a multiple of3, so we printFizz. -
5is a multiple of5, so we printBuzz. -
6is a multiple of3, so we printFizz. -
7and8are not multiples of either3or5, so we print the same number. -
9is a multiple of3, so we printFizz. -
10is a multiple of5, so we printFizz. -
11is not a multiple of either3or5, so we print the same number. -
12is a multiple of3, so we printFizz. -
13and14are not multiples of either3or5, so we print the same number. -
15is a multiple of both3and5, so we printFizzBuzz.
Implementation in Python
We will use a for-in-range loop to solve this problem.
In the code snippet below, we use a for-in-range loop to traverse numbers from 1 to 100.
Note that we use
101; the loop won’t include last element, so it goes up to100.
Use if-elif-else to check if the number is divisible by 3 or 5 or both.
- Check with both the numbers and then check for the numbers individually, as shown in the code below.
- If the number is not divisible by neither
3nor5, then print the same number.
#for loop that traverses numbers from 1 to 100for i in range(1,101):#check if number is divisible by both 3 and 5if(i%3==0 and i%5==0):print("FizzBuzz")#check if number is divisible by 3elif(i%3 == 0):print("Fizz")#check if number is divisible by 5elif(i%5 == 0):print("Buzz")#if not divisible by either of them print the ielse:print(i)