In Python, we often need to repeat actions or make decisions based on certain conditions. This is where loops and conditionals come in. Loops allow you to repeat a block of code, while conditionals let you run specific code only when certain conditions are met.
A conditional statement allows us to execute a block of code only if a certain condition is true. The basic structure is:
if condition:
# code to run if condition is true
else:
# code to run if condition is false
Here’s an example of using an if
statement:
age = 18
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
In this example, the condition age >= 18
is evaluated. If it is true, the code under the if
block is executed (printing "You are an adult"). If it is false, the code under the else
block runs (printing "You are a minor"). This allows us to make decisions within our programs.
Loops help us execute a block of code multiple times. Python has several types of loops, with the for
and while
loops being the most common. Here’s an example using a for
loop:
for i in range(5):
print(i)
The range(5)
function generates numbers from 0 to 4, and the for
loop repeats the print(i)
statement for each number. Loops are especially useful when you need to perform a task multiple times or iterate over a collection of data.
We can combine loops and conditionals to perform actions based on conditions during each iteration of a loop. Here’s an example that prints whether each number from 1 to 10 is even or odd:
for i in range(1, 11):
if i % 2 == 0:
print(i, "Even")
else:
print(i, "Odd")
Write a Python program that uses a loop to print the numbers from 1 to 20. For each number, print "Fizz" if the number is divisible by 3, "Buzz" if it is divisible by 5, and "FizzBuzz" if it is divisible by both.