Chapter 9

Control Flow

Make decisions and repeat actions - the power to control your program's flow!

🚦 What is Control Flow?

Control flow determines the order in which your code executes. By default, Python runs code line by line from top to bottom. But with control flow, you can:

  • Make decisions - execute code only when certain conditions are met
  • Repeat actions - run the same code multiple times
  • Skip code - jump over certain parts based on conditions

Real-Life Analogy

Think about your daily routine:

  • Conditionals (if/else): "If it's raining, take an umbrella. Else, don't."
  • Loops (while/for): "While you're hungry, keep eating." or "For each dish on the menu, read the description."

Control flow gives your programs the ability to make intelligent decisions and handle repetitive tasks!

🔍 How Python Evaluates Conditions

Python uses Boolean logic to make decisions. Every condition evaluates to either True or False. Based on this, Python decides which code to execute.

🔀 if Statements - Making Decisions

The if statement lets you execute code only when a condition is True.

if condition:
    # Code to run if condition is True
    pass

Example 1: Age Check

Output will appear here...

Example 2: Temperature Check

Output will appear here...

Example 3: Membership Check

Output will appear here...

💡 Common Comparison Operators

  • == - Equal to
  • != - Not equal to
  • > - Greater than
  • < - Less than
  • >= - Greater than or equal to
  • <= - Less than or equal to
  • in - Check if item exists in a collection

🔄 elif and else - Multiple Conditions

elif (else if) lets you check multiple conditions in sequence.

else provides a default action when no conditions are True.

Example 1: Grade Checker

Output will appear here...

Example 2: Weather Decision

Output will appear here...

Example 3: Age Categories

Output will appear here...

🔍 How Python Processes if/elif/else

  1. Python checks the if condition first
  2. If True, it runs that block and skips the rest
  3. If False, it checks each elif in order
  4. If all conditions are False, it runs the else block
  5. Only ONE block ever executes!

Nested Conditionals

Example 1: Login System

Output will appear here...

Example 2: Ticket Pricing

Output will appear here...

🔗 Logical Operators - Combining Conditions

Logical operators let you combine multiple conditions:

  • and - Both conditions must be True
  • or - At least one condition must be True
  • not - Reverses the condition

Example 1: Using 'and'

Output will appear here...

Example 2: Using 'or'

Output will appear here...

Example 3: Using 'not'

Output will appear here...

Example 4: Complex Combinations

Output will appear here...

Example 5: Membership with 'and'

Output will appear here...

💡 Truth Table for Logical Operators

and:
True  and True  = True
True  and False = False
False and True  = False
False and False = False

or:
True  or True  = True
True  or False = True
False or True  = True
False or False = False

not:
not True  = False
not False = True

🔁 while Loops - Repeat While Condition is True

A while loop repeats code as long as a condition is True. Be careful - if the condition never becomes False, you'll have an infinite loop!

Example 1: Count Up

Output will appear here...

Example 2: Countdown

Output will appear here...

Example 3: Sum Numbers

Output will appear here...

⚠️ Avoiding Infinite Loops

Always make sure your loop condition will eventually become False!

# ✗ BAD - Infinite loop
# count = 1
# while count <= 5:
#     print(count)
#     # Forgot to increment count!

# ✓ GOOD - Loop will end
count = 1
while count <= 5:
    print(count)
    count += 1  # Condition will eventually be False

🔂 for Loops - Iterate Over Sequences

A for loop iterates over a sequence (like a list, string, or range). It's perfect when you know how many times you want to loop!

Example 1: Loop Through List

Output will appear here...

Example 2: Loop with Calculations

Output will appear here...

Example 3: Loop Through String

Output will appear here...

Example 4: Calculate Total

Output will appear here...

Example 5: Using enumerate()

Output will appear here...

Looping Through Dictionaries

Example 1: Loop Through Keys

Output will appear here...

Example 2: Loop Through Values

Output will appear here...

Example 3: Loop Through Items

Output will appear here...

Example 4: Grade Report

Output will appear here...

📊 The range() Function

range() generates a sequence of numbers. It's perfect for when you want to repeat something a specific number of times!

  • range(stop) - from 0 to stop-1
  • range(start, stop) - from start to stop-1
  • range(start, stop, step) - from start to stop-1, incrementing by step

Example 1: Basic range(stop)

Output will appear here...

Example 2: range(start, stop)

Output will appear here...

Example 3: range with Step

Output will appear here...

Example 4: Countdown

Output will appear here...

Example 5: Multiplication Table

Output will appear here...

🔍 Why range() is Efficient

range() doesn't actually create a list of all numbers in memory. Instead, it generates numbers one at a time as needed. This makes it very memory-efficient, even for huge ranges like range(1000000)!

🎮 Loop Control - break and continue

break - Exits the loop immediately

continue - Skips the rest of the current iteration and moves to the next one

Using break

Example 1: Search for Number

Output will appear here...

Example 2: Login System

Output will appear here...

Example 3: Find First Even

Output will appear here...

Using continue

Example 1: Skip Odd Numbers

Output will appear here...

Example 2: Skip Negatives

Output will appear here...

Example 3: Process Valid Orders

Output will appear here...

Example 4: Filter Items

Output will appear here...

💡 break vs continue

  • break: "Stop the loop completely!"
  • continue: "Skip this iteration, but keep going!"

📺 Video Resources

Watch these videos to master control flow:

Python Conditionals

Corey Schafer

Complete guide to if/elif/else statements and logical operators.

Watch Video

Python Loops

Programming with Mosh

Master while and for loops with practical examples.

Watch Video

Control Flow in Python

Tech With Tim

Understand break, continue, and advanced loop control.

Watch Video

🤖 AI Learning Prompts

Use these prompts to deepen your understanding:

Understanding Conditionals

Help me master Python conditionals:

1. Explain if/elif/else with real-world examples
2. Show me 10 different conditional patterns
3. How do logical operators (and/or/not) work?
4. Give me practice problems for nested conditionals
5. What are common mistakes with conditions?

Include step-by-step examples!

Mastering Loops

I want to become an expert with Python loops:

1. What's the difference between while and for loops?
2. When should I use each type of loop?
3. Show me 15 examples of practical loops
4. How does range() work internally?
5. Give me exercises for break and continue

Make it practical with real applications!

Practical Applications

Help me apply control flow to real problems:

1. Show me how to build a menu system with loops
2. How do I validate user input with conditionals?
3. Give me 5 mini-projects using control flow
4. How do I avoid infinite loops?
5. Show me patterns for iterating through data

Include complete working examples!

✏️ Practice Exercises

Challenge 1: Number Guessing Game

Task: Create a number guessing game using loops and conditionals.

Output will appear here...

Challenge 2: Prime Number Checker

Task: Check if numbers are prime using loops.

Output will appear here...

Challenge 3: Multiplication Table Generator

Difficulty: Easy | Time: 10 minutes

Task: Create a multiplication table for a given number using a for loop.

  • Ask for a number from the user (use a variable for simulation)
  • Display multiplication table from 1 to 10
  • Format output neatly
Output will appear here...

Challenge 4: Pattern Printing

Difficulty: Medium | Time: 15 minutes

Task: Print different patterns using nested loops.

  • Create a right triangle pattern with asterisks
  • Create a pyramid pattern
  • Create a number pyramid
Output will appear here...

Challenge 5: Sum of Even Numbers

Difficulty: Medium | Time: 15 minutes

Task: Calculate the sum of all even numbers in a range.

  • Find all even numbers from 1 to 100
  • Calculate their sum using a loop
  • Count how many even numbers there are
  • Calculate the average of even numbers
Output will appear here...

Challenge 6: Fibonacci Sequence

Difficulty: Hard | Time: 20 minutes

Task: Generate the Fibonacci sequence using loops.

  • Generate the first 15 Fibonacci numbers
  • Display each number in the sequence
  • Bonus: Check if any number is greater than 100
Output will appear here...

🎯 Knowledge Check

Test your understanding of control flow!

Question 1: What happens when an if condition is False?

Question 2: What's the difference between while and for loops?

Question 3: What does range(5) generate?

Question 4: What does break do in a loop?

Question 5: What does and require for a condition to be True?

🎓 Congratulations!

You've mastered control flow! You can now make your programs intelligent with conditionals and efficient with loops. These are fundamental skills you'll use in every Python program!