In this post, we will see how to program Fizzbuzz in Python.
As per wikipedia,
Fizz buzz is a group word game for children to teach them about division.
Here are the rules of the game:
- First player starts the game by saying number 1.
- Next player says next number but fun part is
- If number is divisible by
3
, then player need to sayFizz
- If number is divisible by
5
, then player need to sayBuzz
- If number is divisible by
3
and5
both, then player need to sayFizzBuzz
For example:
If there are 20 children then Number will be printed as below:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz
Read also: FizzBuzz implementation in java
Simple FizzBuzz Python solution
Here is simple FizzBuzz Python solution
class FizzbuzzGame(object): def fizzBuzzImpl(self, number): fizzBuzzList = [] for i in range(1,number+1): if i%3== 0 and i%5==0: fizzBuzzList.append("FizzBuzz") elif i%3==0: fizzBuzzList.append("Fizz") elif i%5 == 0: fizzBuzzList.append("Buzz") else: fizzBuzzList.append(str(i)) return fizzBuzzList fb = FizzbuzzGame() print("FizzBuzz number are:") print(fb.fizzBuzzImpl(20))
Output of above program will be:
FizzBuzz number are:
[‘1’, ‘2’, ‘Fizz’, ‘4’, ‘Buzz’, ‘Fizz’, ‘7’, ‘8’, ‘Fizz’, ‘Buzz’, ’11’, ‘Fizz’, ’13’, ’14’, ‘FizzBuzz’, ’16’, ’17’, ‘Fizz’, ’19’, ‘Buzz’]
[‘1’, ‘2’, ‘Fizz’, ‘4’, ‘Buzz’, ‘Fizz’, ‘7’, ‘8’, ‘Fizz’, ‘Buzz’, ’11’, ‘Fizz’, ’13’, ’14’, ‘FizzBuzz’, ’16’, ’17’, ‘Fizz’, ’19’, ‘Buzz’]
That’s all about FizzBuzz program in Python.