If you’re learning to code, you’ll almost certainly encounter the FizzBuzz problem. It’s a classic programming challenge often used in interviews to test basic logic and control flow. The rules are simple, but it’s a great exercise for practicing loops and conditional statements.
📜 The Rules of FizzBuzz
The goal is to loop through numbers from 1 to 100 and for each number, print one of the following:
- “Fizz” if the number is divisible by 3.
- “Buzz” if the number is divisible by 5.
- “FizzBuzz” if the number is divisible by both 3 and 5.
- The number itself, if none of the above conditions are true.
➗ Using the Modulo Operator
The key to solving FizzBuzz is the modulo operator (%
). This operator gives you the remainder of a division. If `number % 3` is equal to 0, it means the number is perfectly divisible by 3. We can use this inside `if` statements to check our conditions.
💻 A Step-by-Step Solution
First, we need a loop to go through numbers 1 to 100. A for
loop with `range(1, 101)` is perfect for this. Inside the loop, we use an `if-elif-else` chain to check the conditions in the correct order. It’s important to check for divisibility by *both* 3 and 5 first, because if we checked for just 3 first, we would print “Fizz” for a number like 15 and never get to the “FizzBuzz” check.for num in range(1, 101):
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)
And that’s it! While simple, FizzBuzz is a fantastic way to solidify your understanding of fundamental programming concepts.
—
Stephenson, Ben. The Python Workbook: A Brief Introduction with Exercises and Solutions. 3rd ed., Springer, 2025.
More Topics
- How to Pass Command Line Arguments to Your Python Script
- How to Solve the Pythagorean Theorem with a Python Script
- What’s the Difference Between Syntax, Runtime, and Logic Errors in Python?
- What Are Dictionaries in Python and How Do You Use Them?
- Thinking Recursively: A Beginner’s Introduction to Recursion in Python
- How to Read and Write Files in Python
- How to Handle Errors Gracefully in Python with Try and Except