Introduction
In this program, we will explore how to print the numbers from 1 to 100 using Python,
but with some special rules. For example, if the number is divisible by 3, we will print
“Fizz”, if divisible by 5, we will print “Buzz”, and if divisible by both 3 and 5,
we will print “FizzBuzz”. This type of problem is commonly known as the “FizzBuzz” problem.
Objective
The goal of this program is to:
- Print numbers from 1 to 100.
- Apply special conditions for divisibility by 3, 5, or both.
- Learn basic loops and conditional statements in Python.
Python Code
# Python program to print numbers from 1 to 100 with special rules
# 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")
else:
# If the number is not divisible by 3 or 5, print the number itself
print(num)
Explanation of the Program
This Python program follows these steps:
- We use a
for
loop to iterate over the numbers from 1 to 100. The range functionrange(1, 101)
generates numbers from 1 to 100. - Inside the loop, we first check if the number is divisible by both 3 and 5 using the modulo operator (%). If the remainder of dividing the number by 3 and 5 is 0, we print “FizzBuzz”.
- If the number is divisible only by 3, we print “Fizz”. This is checked using the condition
num % 3 == 0
. - If the number is divisible only by 5, we print “Buzz”, checked with
num % 5 == 0
. - If the number is divisible by neither 3 nor 5, we simply print the number itself.
The if
, elif
, and else
statements help in executing different code blocks based on the conditions.
How to Run the Program
To run this program, you need to follow these steps:
- Install Python on your machine if you haven’t already. You can download it from here.
- Open any text editor or an IDE (like PyCharm, VS Code, or IDLE).
- Create a new Python file (e.g.,
fizzbuzz.py
) and paste the code above into the file. - Save the file.
- Open the command line or terminal, navigate to the folder where the file is saved, and run the program using the command
python fizzbuzz.py
. - The program will display numbers from 1 to 100, following the rules explained.