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
Example 2: Temperature Check
Example 3: Membership Check
💡 Common Comparison Operators
==- Equal to!=- Not equal to>- Greater than<- Less than>=- Greater than or equal to<=- Less than or equal toin- 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
Example 2: Weather Decision
Example 3: Age Categories
🔍 How Python Processes if/elif/else
- Python checks the
ifcondition first - If True, it runs that block and skips the rest
- If False, it checks each
elifin order - If all conditions are False, it runs the
elseblock - Only ONE block ever executes!
Nested Conditionals
Example 1: Login System
Example 2: Ticket Pricing
🔗 Logical Operators - Combining Conditions
Logical operators let you combine multiple conditions:
and- Both conditions must be Trueor- At least one condition must be Truenot- Reverses the condition
Example 1: Using 'and'
Example 2: Using 'or'
Example 3: Using 'not'
Example 4: Complex Combinations
Example 5: Membership with 'and'
💡 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
Example 2: Countdown
Example 3: Sum Numbers
⚠️ 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
Example 2: Loop with Calculations
Example 3: Loop Through String
Example 4: Calculate Total
Example 5: Using enumerate()
Looping Through Dictionaries
Example 1: Loop Through Keys
Example 2: Loop Through Values
Example 3: Loop Through Items
Example 4: Grade Report
📊 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-1range(start, stop)- from start to stop-1range(start, stop, step)- from start to stop-1, incrementing by step
Example 1: Basic range(stop)
Example 2: range(start, stop)
Example 3: range with Step
Example 4: Countdown
Example 5: Multiplication Table
🔍 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
Example 2: Login System
Example 3: Find First Even
Using continue
Example 1: Skip Odd Numbers
Example 2: Skip Negatives
Example 3: Process Valid Orders
Example 4: Filter Items
💡 break vs continue
- break: "Stop the loop completely!"
- continue: "Skip this iteration, but keep going!"
📺 Video Resources
Watch these videos to master control flow:
🤖 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.
Challenge 2: Prime Number Checker
Task: Check if numbers are prime using loops.
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
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
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
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
🎯 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!