In Python, control structures are the building blocks of logic that allow you to dictate the flow of your program's execution. They let you make decisions, repeat actions, and handle errors, moving beyond simple, top-to-bottom instruction execution.
1. Conditional Branching (if, elif, else)
Conditional statements allow your program to execute certain blocks of code only if a specific condition is met. This is how a program makes decisions.
- if: The if statement runs a block of code only if its condition is True.
- elif: Short for "else if," this statement lets you check for another condition if the preceding if (or elif) condition was False.
- else: This is a catch-all that runs a block of code if none of the preceding if or elif conditions were True.
Example:
Python
age = 18
if age < 13:
print("You are a child.")
elif age < 20:
print("You are a teenager.")
else:
print("You are an adult.")
# Output: You are a teenager.
2. Looping (for and while)
Loops are used to execute a block of code repeatedly.
for Loops
A for loop is used for iterating over a sequence (like a list, tuple, string, or range). It runs once for each item in the sequence.
Example:
Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I have a {fruit}.")
# Output:
# I have a apple.
# I have a banana.
# I have a cherry.
while Loops
A while loop repeats a block of code as long as a certain condition is true. It's useful when you don't know in advance how many times you need to loop.
Example:
Python
count = 0
while count < 5:
print(f"Count is: {count}")
count += 1 # Increment the count to eventually stop the loop
# Output:
# Count is: 0
# Count is: 1
# Count is: 2
# Count is: 3
# Count is: 4
3. Exception Handling (try, except)
Exception handling is a crucial control structure for managing errors gracefully. It allows your program to "try" a block of code that might cause an error, and if it does, "catch" the error and run a different block of code instead of crashing.
- try: The try block contains the code that might raise an exception (error).
- except: If an exception occurs in the try block, the code in the except block is executed. You can specify which type of error to catch.
Example:
Python
try:
numerator = 10
denominator = 0
result = numerator / denominator
print(result)
except ZeroDivisionError:
print("Error: You cannot divide by zero!")
# Output: Error: You cannot divide by zero!