Control structures are fundamental building blocks of programming that allow developers to control the flow of execution in a program. These structures enable programs to make decisions, repeat actions, and choose between different paths based on conditions or logic. In Python, control structures come in three main types:
- Conditional Statements (if, elif, else)
- Loops (for, while)
- Control Flow Altering Statements (break, continue, pass)
In this detailed guide, we will explore each of these control structures, their significance, and how they are used in Python with clear examples.
Conditional Statements
Conditional statements are used to execute code only if certain conditions are true. Python provides three types of conditional statements: if, elif, and else. They allow the program to branch into different directions based on specified conditions.
if Statement
The if statement evaluates a condition (expression) and executes the block of code only if the condition is True. If the condition is False, the block of code is skipped.
Syntax:
if condition:
# Code to execute if condition is true
Example:
age = 18
if age >= 18:
print("You are eligible to vote.")
Here, the condition age >= 18 is True, so the message “You are eligible to vote.” is printed.
elif Statement
The elif (short for “else if”) statement allows for multiple conditions to be checked sequentially. If the if condition is False, Python evaluates the elif condition. If it is True, the corresponding block of code is executed.
Syntax:
if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition2 is true
Example:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
In this example, the program checks multiple conditions for the score. Since score is 85, the elif score >= 80 block is executed, printing “Grade: B.”
else Statement
The else statement provides a fallback when none of the preceding conditions are True. It catches all cases not handled by if or elif.
Syntax:
if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition2 is true
else:
# Code to execute if none of the above conditions are true
Example:
score = 60
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Here, the else statement is executed because none of the conditions (score >= 90, score >= 80, score >= 70) are True, so the output is “Grade: F.”
Nested if Statements
You can also nest if statements inside other if statements to check for more specific conditions.
Example:
age = 20
has_id = True
if age >= 18:
if has_id:
print("You are eligible to vote.")
else:
print("Please bring an ID to vote.")
else:
print("You are not eligible to vote.")
In this example, the if block inside another if checks both age and possession of an ID.
Loops
Loops are used to repeat a block of code multiple times. Python supports two types of loops: for loops and while loops.
for Loop
A for loop is used to iterate over a sequence (like a list, tuple, or string) and execute a block of code for each item in the sequence.
Syntax:
for item in sequence:
# Code to execute for each item
Example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
This for loop iterates through the fruits list and prints each fruit. The output will be:
apple
banana
cherry
Using range() in a for Loop
The range() function generates a sequence of numbers, making it useful for iterating a specific number of times.
Example:
for i in range(1, 6):
print(i)
This loop will print the numbers from 1 to 5:
1
2
3
4
5
while Loop
A while loop repeats as long as a specified condition is True. Once the condition becomes False, the loop stops.
Syntax:
while condition:
# Code to execute while the condition is true
Example:
count = 1
while count <= 5:
print(count)
count += 1
This loop prints numbers from 1 to 5 and stops when count becomes 6.
Infinite Loop
If the condition in a while loop never becomes False, it creates an infinite loop, which continues to run endlessly. Be cautious of this!
while True:
print("This is an infinite loop")
Nested Loops
You can nest a loop inside another loop to handle more complex scenarios, like iterating through a matrix (list of lists).
Example:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for num in row:
print(num, end=" ")
print()
This code will print each element in the matrix in a grid format:
1 2 3
4 5 6
7 8 9
Control Flow Altering Statements
Python provides special statements to alter the normal flow of loops: break, continue, and pass.
break Statement
The break statement is used to exit a loop prematurely when a certain condition is met.
Example:
for i in range(1, 10):
if i == 5:
break
print(i)
This loop will stop once i equals 5, so the output will be:
1
2
3
4
continue Statement
The continue statement skips the rest of the code inside the loop for the current iteration and moves to the next iteration.
Example:
for i in range(1, 6):
if i == 3:
continue
print(i)
Here, the number 3 is skipped, so the output will be:
1
2
4
5
pass Statement
The pass statement does nothing and is used when a statement is required syntactically, but you don’t want any action to be taken.
Example:
for i in range(1, 6):
if i == 3:
pass # Do nothing for 3
print(i)
The output will be:
1
2
3
4
5
In this case, the loop still processes all numbers, and pass just acts as a placeholder for 3.
Summary
Control structures in Python, including conditional statements, loops, and control flow altering statements, are critical for writing efficient and dynamic programs. They allow you to manage how and when certain parts of your code are executed. By mastering these control structures, you’ll be able to solve a wide variety of programming challenges and write more structured, maintainable code.
Discover more from lounge coder
Subscribe to get the latest posts sent to your email.