Control Flow & Loops in Python
In Python, control flow statements enable you to make decisions and repeat actions based on certain conditions. The two primary control flow constructs are if statements and loops. In this article, we’ll explore how to use these constructs effectively.
If Statements
If statements allow you to execute certain blocks of code only if specific conditions are met.
Basic If Statement
The basic structure of an if statement is:
if condition:
# Code to execute if the condition is True
Example:
age = 18
if age >= 18:
print("You are an adult.")
If-Else Statement
The if-else statement lets you execute one block of code if the condition is true and another block if it is false.
if condition:
# Code to execute if the condition is True
else:
# Code to execute if the condition is False
Example:
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
If-Elif-Else Statement
The if-elif-else statement allows you to check multiple conditions.
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
else:
# Code to execute if both conditions are False
Example:
age = 20
if age < 13:
print("You are a child.")
elif age < 20:
print("You are a teenager.")
else:
print("You are an adult.")
Loops
Loops are used to repeat a block of code multiple times.
For Loop
A for loop is used to iterate over a sequence (like a list, tuple, or string).
for item in sequence:
# Code to execute for each item
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Using Range with For Loop
The range()
function generates a sequence of numbers.
for i in range(start, stop, step):
# Code to execute for each number in the range
start
(optional): The starting value (default is 0).stop
: The stopping value (not inclusive).step
(optional): The difference between each number (default is 1).
Example:
for i in range(1, 6):
print(i)
While Loop
A while loop repeats as long as a condition is true.
while condition:
# Code to execute while the condition is True
Example:
count = 1
while count <= 5:
print(count)
count += 1
Breaking Out of Loops
The break
statement is used to exit a loop prematurely.
Example:
for i in range(1, 11):
if i == 5:
break
print(i)
Skipping Iterations
The continue
statement skips the current iteration and proceeds to the next iteration.
Example:
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)
Nested Loops
Loops can be nested within each other to perform more complex tasks.
Example:
for i in range(1, 4):
for j in range(1, 4):
print(f"i = {i}, j = {j}")
Real-Time Example: Grading System
Let’s create a simple grading system that assigns letter grades based on numerical scores.
# Grading system
score = int(input("Enter your score: "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Your grade is:", grade)
Exercises
- Write a program that prints the first 10 Fibonacci numbers.
- Create a program that checks if a given number is prime.
- Write a script that prints a multiplication table for numbers 1 through 5.
Conclusion
In this article, we’ve covered the basics of control flow in Python using if
statements and loops. These constructs are fundamental for making decisions and repeating actions in your programs. In the next article, we’ll explore functions and how to write reusable code in Python. Happy coding!