Wednesday, 11 January 2017

How to use if-elif-else in Python using the FizzBuzz problem

What is fizzbuzz problem?

It is one of the popular and very simple interview questions for developers. FizzBuzz  problem is to write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

Code:


print 'Showing fizzBuzz numbers from 1 to 20'
for num in range(1,20):
 if num%3== 0 and num%5 == 0:
  print 'fizzbuzz'
 elif num%3 ==0:
  print 'fizz'
 elif num%5 ==0:
  print 'buzz'
 else:
  print num 

Execution:

 

No comments:

Post a Comment