Welcome to Fizz Buzz in Every Language! In this series, we’ll be implementing Fizz Buzz in as many languages as possible. Up first, let’s implement Fizz Buzz in Python.
Today is bit special because we have an article written by someone in the community, samdoj. Don’t forget to thank them for their contribution in the comments!
If you don’t know anything about Python, we recommend checking out Hello World in Python. At any rate, let’s dive in!
Table of Contents
Fizz Buzz in Python
Let’s start by looking at the complete Fizz Buzz algorithm in Python:
for i in range(1, 101): line = '' if i % 3 == 0: line += "Fizz" if i % 5 == 0: line += "Buzz" if not line: line += str(i) print(line)
Before we dig into the code too much, let’s take a look at the rules:
If a number is divisible by 3, print the word ‘Fizz’ instead of the number. If the number is divisible by 5, print the word ‘Buzz’ instead of the number. Finally, if the number is divisible by both 3 and 5, print ‘FizzBuzz’ instead of the number. Otherwise, just print the number.
You can test for divisibility using the modulo operator. The modulo operator divides two numbers and yields the remainder, so
j is 0 if
i is divisible by
j. In Python, this is written as
i % j. Then, it’s a simple matter of checking whether
i % 3 == 0 or
i % 5 == 0.
You’ll notice first how everything is properly indented. This is not just good code style, Python actually enforces it. There’s no need to declare variables as Python is what’s called a weakly typed language. That means it can figure out what type a variable should be on the fly.
In the very first line, we’ll notice a loop:
for i in range(1, 101):
Here, we loop through all the numbers from 1 to 100.
From there, we set the variable
line to an empty string and begin our testing:
line = '' if i % 3 == 0: line += "Fizz" if i % 5 == 0: line += "Buzz" if not line: line += str(i)
If the number is divisible by 3, as explained above, we add the word “Fizz” to the empty string. If it’s divisible by 5, we add the word “Buzz”. Notice the efficiency here. We don’t need
and because by simply adding “Buzz”, we meet the requirement for the case where the number is divisible by 3 and 5, or just 5. Then we add
i to the empty string if the string is still empty.
'' all return false when they’re used in logical comparisons.
Finally, we print the result of
line on every iteration:
Since we declare an empty string at every iteration, we don’t have to worry about
line containing any junk from the previous iteration.
How to Run the Solution
Alternatively, you can always copy the source code into an online Python interpreter and hit run.
Sample Programs in Every Language
And, there you have it! We’ve successfully written a program to perform the Fizz Buzz algorithm in Python.
If you liked this article, don’t forget to give it a share. Also, remember that you can contribute to this series by dropping your suggestions in the comments or forking the GitHub repository.