The FizzBuzz problem is a well-known coding exercise often used to evaluate basic programming skills. The task is to print the numbers from 1 to 100, but with the following rules:
- For multiples of 3, print “Fizz” instead of the number.
- For multiples of 5, print “Buzz” instead of the number.
- For multiples of both 3 and 5, print “FizzBuzz”.
This problem helps demonstrate an understanding of loops, conditionals, and modular arithmetic. The solution will involve iterating through numbers, applying the given rules, and printing the appropriate result for each number.
Objective
The goal is to implement a Python program that:
- Iterates through numbers 1 to 100.
- Prints “Fizz” for multiples of 3.
- Prints “Buzz” for multiples of 5.
- Prints “FizzBuzz” for numbers that are multiples of both 3 and 5.
- Prints the number itself if it is neither a multiple of 3 nor 5.
Python Code for FizzBuzz
# FizzBuzz Program in Python
# Loop through numbers from 1 to 100
for num in range(1, 101):
# Check if the number is divisible by both 3 and 5
if num % 3 == 0 and num % 5 == 0:
print("FizzBuzz")
# Check if the number is divisible by 3
elif num % 3 == 0:
print("Fizz")
# Check if the number is divisible by 5
elif num % 5 == 0:
print("Buzz")
# If the number is neither divisible by 3 nor 5, print the number
else:
print(num)
Explanation of the Program Structure
The program is structured in a simple loop that iterates over the range of numbers from 1 to 100. The key component of the logic is the use of conditional statements to check divisibility using the modulus operator (%).
Breakdown of the Code:
- for num in range(1, 101):
This initializes a loop that runs through the numbers 1 to 100. - if num % 3 == 0 and num % 5 == 0:
This condition checks whether the current number is divisible by both 3 and 5 (i.e., a multiple of 15). If true, it prints “FizzBuzz”. - elif num % 3 == 0:
If the first condition is false, this checks whether the number is divisible by 3, and prints “Fizz” if true. - elif num % 5 == 0:
Similarly, if neither of the previous conditions is true, this checks for divisibility by 5 and prints “Buzz” if the condition is satisfied. - else:
If none of the conditions are met, the number itself is printed.
How to Run the Program
To run this Python program, follow these steps:
-
- Open a text editor and copy the code into a new file.
- Save the file with a .py extension, for example,
fizzbuzz.py
. - Ensure that you have Python installed on your system (Python 3.x is recommended).
- Open a terminal or command prompt window.
- Navigate to the directory where you saved
fizzbuzz.py
. - Run the program by typing the following command and pressing Enter:
python fizzbuzz.py
- You should now see the numbers from 1 to 100 printed on the screen with “Fizz”, “Buzz”, and “FizzBuzz” as described in the problem statement.