AI ProgrammingAcademy

Example Lesson: Control Structures

Master conditional statements and loops through sports, shopping, and weather examples

Optional math support in the Sample Module

Start with Foundations—no advanced math required to begin. Refresh numbers, formulas and statistics, then prepare for Professional with worked Linear Algebra and Calculus lessons. This free preparation is optional, not an exam or certificate prerequisite.

Explore the Sample Module

Learning Objectives

  • Master if/else conditional statements

    Learn to create decision-making structures in your code using if, else, and elif statements. Understand how to evaluate conditions using comparison operators and combine multiple conditions with logical operators. Practice writing clear, efficient conditional blocks that execute different code paths based on specific criteria, enabling your programs to respond intelligently to different situations.

  • Implement for and while loops effectively

    Develop skills to create and control repetitive tasks using for and while loops. Learn when to use each loop type based on your specific needs: for loops for iterating over sequences with a known number of iterations, and while loops for continuing until a condition changes. Master loop variables, iteration patterns, and techniques for processing collections of data efficiently.

  • Use break and continue statements

    Learn to control the flow of loops with break statements to exit loops early when certain conditions are met, and continue statements to skip the current iteration and move to the next one. Understand how these control statements can make your code more efficient and responsive to specific conditions, allowing for more sophisticated loop behavior and preventing unnecessary iterations.

  • Handle multiple conditions with elif statements

    Master the use of elif (else if) statements to create multi-branch decision structures that can handle numerous possible conditions efficiently. Learn to organize conditions logically, understand evaluation order, and write clean, readable code that can process complex decision trees. Practice creating comprehensive conditional structures that cover all possible scenarios while maintaining code clarity.

Core Concepts

Conditional Statements - Making Decisions in Code

Conditional statements are the decision-making backbone of programming. They allow your program to evaluate conditions and execute different code paths based on whether those conditions are true or false. Think of them as the "if-then" logic that mirrors human decision-making processes. Without conditionals, programs would only be able to execute code in a linear, unchanging sequence, making them static and unresponsive to different inputs or situations.

The power of conditional statements lies in their ability to create branching logic, where your program can take different actions based on user input, data values, system states, or any other conditions you define. This makes your applications interactive, adaptive, and intelligent.

if Statement - The Foundation of Decision Making

The if statement is the most fundamental conditional structure. It evaluates a boolean expression (condition) and executes a block of code only if that condition evaluates to true. In Python, conditions can be any expression that returns True or False, including comparisons, logical operations, or function calls that return boolean values.

The if statement can be extended with 'elif' (else if) clauses to handle multiple conditions in sequence, and an 'else' clause to provide a default action when none of the conditions are met. This creates a decision tree that can handle complex logic scenarios.

# Basic if statement - Grade evaluation system
score = 85

if score >= 90:
    print("Outstanding! You got an A!")
elif score >= 80:
    print("Very Good! You got a B!")
elif score >= 70:
    print("Passed! You got a C!")
else:
    print("Need improvement. Please see your teacher.")

# Complex conditions with logical operators
age = 25
has_membership = True
has_insurance = True

if age >= 18 and has_membership and has_insurance:
    print("You can legally drive!")
elif age >= 18 and has_membership:
    print("You need insurance to drive legally.")
elif age >= 18:
    print("You need a license and insurance to drive.")
else:
    print("You must be 18 or older to drive.")

Pro Tip: Python uses indentation to define code blocks. Make sure your indentation is consistent (use 4 spaces) to avoid IndentationError. The colon (:) at the end of if/elif/else statements is required.

Complex Elif Chains - Multi-Condition Decision Making

When you have multiple conditions to check, elif (else if) chains provide an elegant solution. Python evaluates conditions from top to bottom and executes the first matching condition, then skips the rest. This is more efficient than multiple separate if statements and ensures only one condition executes.

Elif chains are perfect for categorization, grading systems, user access levels, and any scenario where you need to check multiple mutually exclusive conditions. The order of conditions matters - place more specific conditions before general ones.

# College admission decision system
gpa = 3.7
sat_score = 1350
extracurriculars = True
recommendation_letters = 2

if gpa >= 3.9 and sat_score >= 1400:
    print("Congratulations! Automatic acceptance with scholarship consideration.")
    status = "accepted_scholarship"
elif gpa >= 3.7 and sat_score >= 1300 and recommendation_letters >= 2:
    print("Congratulations! You've been accepted to our program.")
    status = "accepted"
elif gpa >= 3.5 and extracurriculars:
    print("Your application has been accepted with conditions.")
    status = "conditional"
elif gpa >= 3.0 and sat_score >= 1200:
    print("Your application has been waitlisted.")
    status = "waitlisted"
else:
    print("We're sorry, but your application doesn't meet our requirements.")
    status = "rejected"

# Weather clothing recommendation with nested conditions
temperature = 45  # Fahrenheit
is_raining = False
is_windy = True

if temperature >= 80:
    if is_raining:
        recommendation = "Wear light clothes and bring an umbrella."
    else:
        recommendation = "Wear light clothes and sunscreen."
elif temperature >= 60:
    if is_raining and is_windy:
        recommendation = "Wear a light jacket and bring an umbrella."
    elif is_raining:
        recommendation = "Bring an umbrella."
    else:
        recommendation = "A light jacket might be comfortable."
elif temperature >= 40:
    if is_raining and is_windy:
        recommendation = "Wear a heavy coat and bring an umbrella."
    elif is_windy:
        recommendation = "Wear a heavy coat, it feels colder than it is."
    else:
        recommendation = "Wear a jacket or coat."
else:
    recommendation = "It's very cold! Wear a heavy coat, gloves, and a hat."

print(f"Weather recommendation: {recommendation}")

Best Practice: Order your conditions from most specific to most general. Use logical operators (and, or, not) to combine conditions efficiently. Consider using nested if statements when you have complex, hierarchical decision logic.

Loop Structures - Automating Repetitive Tasks

Loops are fundamental programming constructs that allow you to execute code repeatedly without having to write the same statements multiple times. They are essential for processing collections of data, implementing algorithms, creating patterns, and automating repetitive tasks. Mastering loops is crucial for writing efficient, maintainable code and solving complex programming problems.

Python provides several types of loops, each designed for different scenarios. The choice of loop depends on whether you're iterating over a collection, need a specific number of iterations, or want to continue until a condition changes.

for Loop - Iterating Over Collections

The for loop in Python is designed to iterate over sequences like lists, strings, ranges, and other iterable objects. It's the most commonly used loop because it's clean, readable, and handles the iteration logic automatically. Unlike many other languages, Python's for loop doesn't require manual index management.

Python's for loop can iterate directly over values in a collection, or you can use the range() function to create sequences of numbers. The range() function is particularly useful for creating counting loops or when you need both the index and value.

# Iterating directly over a list
attendance = [15000, 22500, 25000, 18000]
total = 0

for people in attendance:
    total += people
    print(f"Daily attendance: {people:,}")

print(f"Total festival attendance: {total:,}")

# Using range() for counting loops
print("
Countdown:")
for i in range(10, 0, -1):  # Start at 10, stop before 0, step by -1
    print(f"T-minus {i}...")
print("Blast off!")

# Processing with both index and value using enumerate()
students = ["Emily", "Michael", "Sophia", "Jacob"]
grades = [88, 92, 85, 90]

print("
Student Grades:")
for i, student in enumerate(students):
    print(f"{i+1}. {student}: {grades[i]}%")

# Iterating over strings
message = "Python"
print("
Letters in 'Python':")
for letter in message:
    print(f"Letter: {letter}")

Python Advantage: Python's for loop is more intuitive than traditional C-style loops. Use enumerate() when you need both index and value, and zip() to iterate over multiple sequences simultaneously.

while Loop - Condition-Based Repetition

The while loop continues executing as long as a specified condition remains True. It's ideal when you don't know in advance how many iterations you'll need, but you know the condition that should stop the loop. The condition is checked before each iteration, so the loop might not execute at all if the condition is initially False.

While loops are perfect for user input validation, game loops, processing data until a certain condition is met, or implementing algorithms where the number of iterations depends on the data being processed.

# Subway fare collection system
passengers = 0
total_fare = 0
fare_per_person = 2.75
max_capacity = 20

print("Subway fare collection:")
while passengers < max_capacity:
    passengers += 1
    total_fare += fare_per_person
    print(f"Passenger {passengers} paid ${fare_per_person}")
    
    # Stop early if we reach target collection
    if total_fare >= 40:
        print(f"Target collection reached at {total_fare:.2f}")
        break

print(f"Final collection: {total_fare:.2f} from {passengers} passengers")

# User input validation
print("
Password validation:")
while True:
    password = input("Enter a password (min 8 characters): ")
    if len(password) >= 8:
        print("Password accepted!")
        break
    else:
        print(f"Password too short ({len(password)} chars). Try again.")

# Number guessing game
import random
secret_number = random.randint(1, 100)
guesses = 0
max_guesses = 7

print(f"
Guess the number between 1 and 100! You have {max_guesses} tries.")
while guesses < max_guesses:
    try:
        guess = int(input("Enter your guess: "))
        guesses += 1
        
        if guess == secret_number:
            print(f"Congratulations! You guessed it in {guesses} tries!")
            break
        elif guess < secret_number:
            print("Too low!")
        else:
            print("Too high!")
            
        remaining = max_guesses - guesses
        if remaining > 0:
            print(f"You have {remaining} guesses left.")
    except ValueError:
        print("Please enter a valid number.")
        guesses -= 1  # Don't count invalid input

if guesses >= max_guesses and guess != secret_number:
    print(f"Game over! The number was {secret_number}.")

Critical Warning: Always ensure the loop condition will eventually become False, or you'll create an infinite loop! Include a way to modify the condition variable inside the loop body.

Loop Control Statements - Fine-Tuning Loop Behavior

Loop control statements allow you to alter the normal flow of loop execution, providing fine-grained control over when and how loops terminate or skip iterations. These powerful tools enable you to write more efficient algorithms and handle complex scenarios where simple loop conditions aren't sufficient.

Python provides two main loop control statements: 'break' to exit loops early, and 'continue' to skip the current iteration. Understanding when and how to use these statements is crucial for writing efficient, readable code.

break Statement - Early Loop Exit

The break statement completely exits the loop and continues with the code after the loop. It's useful for search algorithms, error conditions, or when you've found what you're looking for.

# Finding the first prime number after 20
print("Finding the first prime number after 20:")
num = 21
while True:  # Infinite loop - we'll break when we find a prime
    is_prime = True
    
    # Check if num is prime
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            is_prime = False
            break  # Break inner loop when factor is found
    
    if is_prime:
        print(f"Found prime number: {num}")
        break  # Break outer loop when prime is found
    
    num += 1

# Search for specific item in a list
students = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
search_name = "Charlie"
found_index = -1

for i, student in enumerate(students):
    if student == search_name:
        found_index = i
        print(f"Found {search_name} at position {i}")
        break  # Stop searching once found

if found_index == -1:
    print(f"{search_name} not found in the list")

continue Statement - Skip Current Iteration

The continue statement skips the rest of the current iteration and moves to the next one. It's perfect for filtering data, skipping invalid inputs, or processing only specific items.

# Processing only odd numbers
print("Processing odd numbers from 1 to 10:")
for i in range(1, 11):
    if i % 2 == 0:  # Skip even numbers
        continue
    print(f"Processing odd number: {i}")
    # Additional processing for odd numbers would go here

# Grade processing - skip invalid grades
grades = [85, -1, 92, 105, 78, 88, 0, 95]
valid_grades = []
total = 0
count = 0

print("
Processing grades (skipping invalid ones):")
for grade in grades:
    if grade < 0 or grade > 100:
        print(f"Skipping invalid grade: {grade}")
        continue  # Skip this iteration
    
    # Process valid grade
    valid_grades.append(grade)
    total += grade
    count += 1
    print(f"Valid grade: {grade}")

if count > 0:
    average = total / count
    print(f"
Average of valid grades: {average:.1f}")
    print(f"Valid grades: {valid_grades}")

# File processing - skip empty lines
lines = ["Hello World", "", "Python Programming", "   ", "Data Science", ""]

print("
Processing non-empty lines:")
for line_num, line in enumerate(lines, 1):
    if not line.strip():  # Skip empty or whitespace-only lines
        continue
    print(f"Line {line_num}: {line}")

Best Practice: Use break and continue judiciously to improve code efficiency and readability. However, overuse can make code harder to follow. Consider refactoring complex loop logic into separate functions when the control flow becomes too complex.

Nested Control Structures - Solving Complex Problems

Combining control structures allows you to solve complex problems by creating sophisticated program logic and data processing algorithms. Nested structures enable you to handle multi-dimensional data, implement complex decision trees, and create powerful algorithms that can process hierarchical information.

While nested structures are powerful, they can also make code harder to read and maintain. The key is finding the right balance between functionality and readability, and knowing when to break complex logic into separate functions.

Nested Loops - Multi-Dimensional Processing

Nested loops are essential for processing 2D data structures, creating patterns, and implementing algorithms that require multiple levels of iteration.

# Creating a multiplication table
print("Multiplication Table (1-5):")
for i in range(1, 6):
    for j in range(1, 6):
        product = i * j
        print(f"{i} x {j} = {product:2d}", end="  ")
    print()  # New line after each row

# Processing a 2D grid (like a game board)
game_board = [
    ['X', 'O', 'X'],
    ['O', 'X', 'O'],
    ['X', 'X', 'O']
]

print("
Game Board Analysis:")
x_count = 0
o_count = 0

for row_num, row in enumerate(game_board):
    for col_num, cell in enumerate(row):
        print(f"Position ({row_num},{col_num}): {cell}")
        if cell == 'X':
            x_count += 1
        elif cell == 'O':
            o_count += 1

print(f"
X count: {x_count}, O count: {o_count}")

# Pattern generation
print("
Star Pattern:")
for i in range(1, 6):
    # Print spaces for alignment
    for j in range(5 - i):
        print(" ", end="")
    # Print stars
    for k in range(i):
        print("* ", end="")
    print()  # New line

Loops with Complex Conditionals

Combining loops with sophisticated conditional logic enables powerful data processing and analysis capabilities.

# Student performance analysis system
students = [
    {"name": "Alice", "scores": [85, 92, 78, 96], "attendance": 95},
    {"name": "Bob", "scores": [76, 84, 88, 82], "attendance": 87},
    {"name": "Charlie", "scores": [95, 89, 93, 91], "attendance": 98},
    {"name": "Diana", "scores": [68, 72, 75, 70], "attendance": 82}
]

print("Student Performance Analysis:")
print("=" * 50)

for student in students:
    name = student["name"]
    scores = student["scores"]
    attendance = student["attendance"]
    
    # Calculate average score
    total_score = sum(scores)
    average_score = total_score / len(scores)
    
    # Determine letter grade
    if average_score >= 90:
        letter_grade = "A"
        performance = "Excellent"
    elif average_score >= 80:
        letter_grade = "B"
        performance = "Good"
    elif average_score >= 70:
        letter_grade = "C"
        performance = "Satisfactory"
    elif average_score >= 60:
        letter_grade = "D"
        performance = "Needs Improvement"
    else:
        letter_grade = "F"
        performance = "Failing"
    
    # Check for attendance issues
    if attendance < 85:
        attendance_status = "Poor attendance - at risk"
    elif attendance < 90:
        attendance_status = "Attendance needs improvement"
    else:
        attendance_status = "Good attendance"
    
    # Generate recommendations
    recommendations = []
    if average_score < 75:
        recommendations.append("Consider tutoring")
    if attendance < 90:
        recommendations.append("Improve attendance")
    if max(scores) - min(scores) > 20:
        recommendations.append("Work on consistency")
    
    # Print student report
    print(f"Student: {name}")
    print(f"  Average Score: {average_score:.1f} ({letter_grade}) - {performance}")
    print(f"  Attendance: {attendance}% - {attendance_status}")
    print(f"  Individual Scores: {scores}")
    
    if recommendations:
        print(f"  Recommendations: {', '.join(recommendations)}")
    else:
        print(f"  Status: Performing well - keep it up!")
    
    print("-" * 30)

Performance Consideration: Be mindful of nested loop complexity. Nested loops can quickly become expensive (O(n²) or worse). For large datasets, consider using more efficient algorithms, built-in functions like map() and filter(), or list comprehensions for better performance.

Python-Specific Features and Best Practices

Python offers several unique features and idioms that make control structures more powerful and readable. Understanding these Python-specific approaches will help you write more efficient, "Pythonic" code that leverages the language's strengths and follows established conventions.

These features distinguish Python from other programming languages and enable you to write more concise, expressive code while maintaining readability and performance.

List Comprehensions - Elegant Data Processing

List comprehensions provide a concise way to create lists using loops and conditions in a single line. They're often more readable and faster than traditional loops for simple data transformations.

# Traditional approach vs List comprehension
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Traditional way
squares = []
for num in numbers:
    if num % 2 == 0:
        squares.append(num ** 2)

# List comprehension way (more Pythonic)
squares = [num ** 2 for num in numbers if num % 2 == 0]
print(f"Squares of even numbers: {squares}")

# Complex example: Processing student data
students = ["alice", "bob", "charlie", "diana"]
formatted_names = [name.title() for name in students if len(name) > 3]
print(f"Formatted names (>3 chars): {formatted_names}")

# Nested list comprehension for 2D data
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(f"Flattened matrix: {flattened}")

# Dictionary comprehension
word_lengths = {word: len(word) for word in ["python", "java", "javascript"]}
print(f"Word lengths: {word_lengths}")

The else Clause with Loops

Python's unique feature: loops can have an else clause that executes only if the loop completes normally (not broken). This is perfect for search operations and validation scenarios.

# Searching with loop-else
numbers = [2, 4, 6, 8, 10]
search_for = 7

for num in numbers:
    if num == search_for:
        print(f"Found {search_for}!")
        break
else:
    print(f"{search_for} not found in the list")

# Prime number checking with while-else
def is_prime(n):
    if n < 2:
        return False
    
    i = 2
    while i * i <= n:
        if n % i == 0:
            return False
        i += 1
    else:
        return True  # Loop completed without finding factors

print(f"Is 17 prime? {is_prime(17)}")
print(f"Is 15 prime? {is_prime(15)}")

# Validation with for-else
passwords = ["abc", "password123", "secure_pass_2024"]
for password in passwords:
    if len(password) >= 8 and any(c.isdigit() for c in password):
        print(f"Valid password found: {password}")
        break
else:
    print("No valid passwords found in the list")

Built-in Functions for Elegant Iteration

Python provides powerful built-in functions that make common iteration patterns more elegant and efficient.

# enumerate() - get index and value
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits, start=1):
    print(f"{index}. {fruit}")

# zip() - iterate over multiple sequences
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

# reversed() - iterate in reverse order
for num in reversed(range(1, 6)):
    print(f"Countdown: {num}")

# sorted() - iterate in sorted order
scores = [85, 92, 78, 96, 88]
for score in sorted(scores, reverse=True):
    print(f"Score: {score}")

# any() and all() - boolean operations on iterables
numbers = [2, 4, 6, 8, 10]
print(f"All even: {all(num % 2 == 0 for num in numbers)}")
print(f"Any greater than 5: {any(num > 5 for num in numbers)}")

Pythonic Tip: Embrace Python's unique features like list comprehensions, the loop-else construct, and built-in functions like enumerate(), zip(), and range(). These make your code more readable and often more efficient than traditional approaches. Remember: "There should be one obvious way to do it" - The Zen of Python.

Practice Exercises

Exercise 1: Baseball Game Statistics

Create a program that analyzes baseball game statistics based on runs scored in each inning.

# Create a program that:
# 1. Takes input for runs scored in each inning
# 2. Calculates total runs and identifies highest scoring inning
# 3. Identifies innings with rallies (3+ runs)
# 4. Generates a game assessment based on scoring patterns

# Your code here:

Exercise 2: Shopping Discount Calculator

Create a program to calculate shopping totals with various discount types.

# Create a program that:
# 1. Calculates subtotal from items and quantities
# 2. Applies membership discounts if applicable
# 3. Applies coupon code discounts if valid
# 4. Applies bulk purchase discounts for orders over $100
# 5. Generates a detailed receipt with all discounts

# Your code here:

Exercise 3: Weather Advisory System

Create a program that generates weather advisories based on current conditions.

# Create a program that:
# 1. Takes input for temperature, conditions, wind speed, and precipitation
# 2. Generates appropriate weather advisories based on conditions
# 3. Provides activity recommendations based on weather
# 4. Formats output as a detailed weather advisory

# Your code here:

Concept Quiz

Test your understanding with this quiz. Select the best answer for each question.

1. What is the output of the following code? x = 10 if x > 5: print('A') elif x > 8: print('B') else: print('C')

2. Which of the following is NOT a valid loop in Python?

3. What will the following code print? count = 0 while count < 5: if count == 3: break print(count) count += 1

4. What is the purpose of the 'continue' statement in loops?

5. What will be the output of this code? for i in range(3): for j in range(2): print(i, j)

Are there any issues that Customer Support should be aware of?

Help optimize our AI programming lessons to ensure student success!

Sign in to send a comment to Customer Support.

Hide Icons