FizzBuzz in Python
Hi Everyone~
I hope all is well and you’re staying warm as it’s getting colder. Today I’ll be writing about FizzBuzz in Python!
If you don’t know what FizzBuzz is, it’s a pretty popular and very easy algorithm interviewers can ask you. Additionally, it’s a good warm up algorithm.
Main idea:
Given a range of numbers, if a number is divisible by 3, by 5 or by both, you’ll append “Fizz”, “Buzz” and/or “FizzBuzz” respectively into a new list and return it.
Here are the steps:
- Create your empty list.
- Use the range function and combine it with a for loop.
- Create conditional logic that states if the number is divisible by 3, 5 or 15, push “Fizz”, “Buzz” or “FizzBuzz” into the list. Else if the current iteration is not divisible by any of the numbers listed, push the number into the list.
- Return the list.
I know I’m being pretty repetitive, but let’s get into it!
list = []for num in range(1,100):
if num % 3 == 0 and num % 5 == 0:
list.append(“FizzBuzz”)
elif num % 3 == 0:
list.append(“Fizz”)
elif num % 5 == 0:
list.append(“Buzz”)
else:
list.append(num) print(list)
And that’s it! it’s so easy! :D
Now you’re a FizzBuzz master :)
Happy Hacking!
-Crystal