3  Control Structures in Python

Control structures are essential in programming as they allow you to dictate the flow of execution in your code. Python provides several control structures, including conditional statements, loops, and error handling.

3.1 Control Structures

3.1.1 if Statement

The if statement is used to execute a block of code only if a specified condition is true. You can use if, elif (else if), and else to build more complex conditions.

3.1.1.1 Basic if Statement

# Basic if statement
age = 18
if age >= 18:
    print("You are an adult.")  # Output: You are an adult.

3.1.1.2 if-elif-else Structure

You can chain multiple conditions using elif and provide a default action using else.

# if-elif-else example
score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")  # Output: Grade: B
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

3.1.1.3 Nested if Statements

if statements can be nested within each other to handle complex conditions.

# Nested if statement
number = 10
if number > 0:
    print("Positive number")  # Output: Positive number
    if number % 2 == 0:
        print("Even number")  # Output: Even number

3.1.2 while Loop

The while loop repeatedly executes a block of code as long as the specified condition is true. It is used when the number of iterations is not known in advance.

3.1.2.1 Basic while Loop

# Basic while loop
count = 1
while count <= 5:
    print(count)  # Output: 1 2 3 4 5
    count += 1

3.1.2.2 while Loop with break and continue

  • break: Exits the loop immediately.
  • continue: Skips the current iteration and moves to the next one.
# Using break and continue in a while loop
num = 0
while num < 10:
    num += 1
    if num == 5:
        continue  # Skip the number 5
    if num == 8:
        break  # Exit the loop when num is 8
    print(num)  # Output: 1 2 3 4 6 7

3.1.3 for Loop

The for loop iterates over a sequence (such as a list, tuple, string, or range). It is used when the number of iterations is known.

3.1.3.1 Basic for Loop

# Basic for loop
for i in range(5):
    print(i)  # Output: 0 1 2 3 4

3.1.3.2 Iterating Over a List

# Iterating over a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)  # Output: apple banana cherry

3.1.3.3 for Loop with break and continue

# Using break and continue in a for loop
for num in range(1, 10):
    if num == 4:
        continue  # Skip number 4
    if num == 7:
        break  # Stop the loop when num is 7
    print(num)  # Output: 1 2 3 5 6

3.1.4 Exception Handling

Exception handling allows you to manage errors gracefully without crashing your program. Use try, except, else, and finally blocks to handle exceptions.

3.1.4.1 Basic Exception Handling with try and except

# Basic try-except block
try:
    result = 10 / 0  # This will raise a ZeroDivisionError
except ZeroDivisionError:
    print("Cannot divide by zero!")  # Output: Cannot divide by zero!

3.1.4.2 Multiple Exceptions

You can handle multiple exceptions by specifying different exception types.

# Handling multiple exceptions
try:
    value = int("abc")  # This will raise a ValueError
except ValueError:
    print("Invalid number format.")  # Output: Invalid number format.
except ZeroDivisionError:
    print("Division by zero is not allowed.")

3.1.4.3 Using else and finally

  • else: Executes if no exception occurs.
  • finally: Executes no matter what, useful for cleanup actions.
# Using else and finally with try-except
try:
    num = 5
    result = num / 1
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print("Division successful:", result)  # Output: Division successful: 5.0
finally:
    print("Execution complete.")  # Output: Execution complete.