Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
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!
Python 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 or on youtube.
Python Interview Question FizzBuzz was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.