Skip to content

2.5 Control Flow – Conditional Statements (if, elif, else), Loops (for, while)

Welcome to this crucial lesson where we’ll explore the concept of control flow in Python. Control flow structures allow us to dictate the order in which our code is executed, making it dynamic and responsive to different scenarios. In this lesson, we’ll focus on conditional statements (if, elif, else) and loops (for, while).

Conditional Statements:

1. The if Statement:

  • Used to execute a block of code if a specified condition is True.
  • Syntax:
if condition:
    # Code to be executed if the condition is True

2. The else Statement:

  • Used to execute a block of code if the preceding if condition is False.
  • Syntax:
if condition:
    # Code to be executed if the condition is True
else:
    # Code to be executed if the condition is False

3. The elif Statement:

  • Allows checking multiple conditions in sequence.
  • Syntax:
if condition1:
    # Code to be executed if condition1 is True
elif condition2:
    # Code to be executed if condition1 is False and condition2 is True
else:
    # Code to be executed if both condition1 and condition2 are False

Loops:

4. The for Loop:

  • Used for iterating over a sequence (e.g., a list, tuple, or string).
  • Syntax:
for variable in sequence:
    # Code to be executed in each iteration

5. The while Loop:

  • Repeats a block of code as long as a specified condition is True.
  • Syntax:
while condition:
    # Code to be executed as long as the condition is True

Example:

Let’s consider an example where we use a combination of conditional statements and loops to identify and print even numbers in a given range:

# Example Code
start = 1
end = 10

for num in range(start, end + 1):
    if num % 2 == 0:
        print(f"{num} is an even number.")
    else:
        print(f"{num} is an odd number.")

Practice Exercise:

Create a Python script that asks the user for their age. Use conditional statements to categorize their age into different groups (e.g., child, teenager, adult) and print an appropriate message.

# Example Practice Exercise
age = int(input("Enter your age: "))

if age < 13:
    print("You are a child.")
elif 13 <= age < 20:
    print("You are a teenager.")
else:
    print("You are an adult.")

Summary:

In this lesson, we’ve explored the power of control flow in Python using conditional statements (if, elif, else) and loops (for, while). Practice writing code with these structures, and feel free to ask questions in the discussion forum. These tools are essential for building flexible and responsive programs, so let’s continue our Python journey with confidence!