Python Interview Question FizzBuzz

Python Interview Question FizzBuzz

Python FizzBuzz Video Tutorial

Write a program that prints the numbers from 1 to 20. 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?.

Method 1: Concatenating Strings

for num in range(1,21): string = “” if num % 3 == 0: string = string + “Fizz” if num % 5 == 0: string = string + “Buzz” if num % 5 != 0 and num % 3 != 0: string = string + str(num) print(string)

Method 2: Use if, elif, and else

for num in range(1, 21): 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)

Concluding Remarks

There are so many different ways to solve the problem so feel free to post your own method!

Image for postPython 2 specific FizzBuzz Method. For Python 3, simply take out first line (from __future__ import print_function)

As always, the code used in this blog post and in the video above is available on my github. Please let me know if you have any questions either here, on youtube, or through Twitter. Next post goes over Prime Numbers using Python. If you want to learn how to utilize the Pandas, Matplotlib, or Seaborn libraries, please consider taking my Python for Data Visualization LinkedIn Learning course. Here is a free preview video.

No Responses

Write a response