Mastering Control Structures in Python: Making Decisions and Loops
When it comes to programming, Control Structures are essential to define the flow of your program. They allow you to make decisions, repeat actions, and control how your code behaves under different conditions. Without control structures, your code would only run in a straight line, which is rarely useful in real-world applications.
In this post, we'll cover the key control structures in Python: conditional statements, loops, and special flow control statements. Let’s dive into how Python handles the flow of execution!
1. Conditional Statements (If-Else)
Conditional statements allow you to execute certain blocks of code based on a specific condition. The most common conditional statements are if
, elif
, and else
.
1.1 Basic if
Statement
The if
statement is used to test a condition. If the condition evaluates to True, the code inside the if
block runs.
age = 20
if age >= 18:
print("You are an adult!")
1.2 Using else
The else
statement lets you define an alternative block of code if the if
condition is False.
age = 16
if age >= 18:
print("You are an adult!")
else:
print("You are a minor!")
1.3 Using elif
(Else-If)
You can chain multiple conditions with elif
(short for "else if"). If the first if
condition fails, Python checks the elif
condition.
age = 20
if age >= 18:
print("You are an adult!")
elif age < 18 and age >= 13:
print("You are a teenager!")
else:
print("You are a child!")
2. Loops in Python
Loops are a way to execute a block of code multiple times. Python has two primary types of loops: for
loops and while
loops.
2.1 The for
Loop
The for
loop is used to iterate over a sequence (like a list, tuple, string, or dictionary).
# Looping through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
2.1.1 Looping Over Strings
You can also loop through each character of a string.
word = "hello"
for letter in word:
print(letter)
2.1.2 Looping Over a Range
If you want to repeat a block of code a specific number of times, you can use the range()
function.
for i in range(5): # Loops from 0 to 4
print(i)
2.2 The while
Loop
The while
loop keeps running as long as the condition evaluates to True
.
count = 0
while count < 5:
print(count)
count += 1 # Increment to avoid infinite loop
3. Special Flow Control Statements
3.1 The break
Statement
The break
statement is used to exit the current loop prematurely, regardless of the loop’s condition. This is helpful when you’ve met your goal and don’t need to continue looping.
for i in range(10):
if i == 5:
break
print(i) # Prints numbers from 0 to 4
3.2 The continue
Statement
The continue
statement skips the current iteration of the loop and moves to the next one. It’s useful when you want to skip certain conditions but continue the loop.
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i) # Prints only odd numbers
3.3 The pass
Statement
The pass
statement is a placeholder. It does nothing, but it’s useful when you need to write a placeholder function or loop that you’ll implement later.
for i in range(5):
if i == 3:
pass # Do nothing for i == 3
print(i)
4. Nested Loops
Sometimes you need a loop inside another loop, which is known as a nested loop. Here’s an example where we loop over a list of lists:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
print(element)
5. For/Else Loop
In Python, a for
loop can have an else
block. The else
block runs when the loop completes all its iterations without hitting a break
statement.
for i in range(5):
print(i)
else:
print("Loop completed without interruption")
However, if the loop is terminated with a break
statement, the else
block will not execute.
6. Real-World Example: Using Loops & Conditionals Together
Let’s put everything into a real-world example. Suppose you have a list of numbers, and you want to check which ones are even or odd and then calculate their squares.
numbers = [2, 3, 5, 6, 8, 9, 10]
for num in numbers:
if num % 2 == 0:
print(f"{num} is even. Its square is {num**2}")
else:
print(f"{num} is odd. Its square is {num**2}")
Wrap-Up
Congratulations! You’ve now mastered the basics of Control Structures in Python. To recap, we’ve covered:
-
Conditional statements (
if
,elif
,else
) -
Loops (
for
andwhile
) -
Special flow control with
break
,continue
, andpass
-
How to use nested loops and for/else loops