Control Flow
If/else, for loops, while loops, and logical operators — the decision-making logic that turns a list of instructions into a smart program.
The thermostat that thinks for itself
You have a thermostat in your home. It does not just display the temperature — it makes decisions. If the room drops below 68 degrees, it turns on the heater. If it rises above 75, it turns on the air conditioning. Otherwise, it does nothing.
That thermostat is running control flow. It checks a condition, and depending on whether that condition is true or false, it takes a different action. Every smart system in the world — from Netflix recommendations to self-driving cars to the spam filter in your email — runs on this same idea: check a condition, make a decision, repeat.
Without control flow, a program is just a list of instructions that runs top to bottom, every time, the same way. With control flow, a program can think.
temperature = 65
if temperature < 68:
print("Turning on the heater")
elif temperature > 75:
print("Turning on the AC")
else:
print("Temperature is comfortable")
That is a thermostat in five lines of Python.
If / elif / else — making decisions
The if statement is the most fundamental control structure in all of programming. It works exactly like a decision in real life.
Think of it as a bouncer at a club door:
age = 21
if age >= 21:
print("Welcome in!") # This runs
elif age >= 18:
print("No drinks for you")
else:
print("Come back in a few years")
The anatomy:
| Part | What it does | Required? |
|---|---|---|
if condition: | Checks the first condition | Yes — always required |
elif condition: | Checks if the first was false, then checks this one | Optional — use 0 or more |
else: | Runs if ALL conditions above were false | Optional — use 0 or 1 |
| Indented block | The code that runs when the condition is true | Yes — 4 spaces per level |
Comparison operators
These are the tools you use inside conditions:
x = 10
print(x == 10) # True (equal to)
print(x != 5) # True (not equal to)
print(x > 5) # True (greater than)
print(x < 20) # True (less than)
print(x >= 10) # True (greater than or equal)
print(x <= 9) # False (less than or equal)
Logical operators — combining conditions
What if you need to check multiple things at once? Use and, or, and not:
age = 25
has_id = True
if age >= 21 and has_id:
print("Welcome in!")
temperature = 72
if temperature < 60 or temperature > 85:
print("Extreme weather alert!")
is_raining = False
if not is_raining:
print("No umbrella needed")
✗ Without AI
- ✗True and True = True
- ✗True and False = False
- ✗False and True = False
- ✗False and False = False
✓ With AI
- ✓True or True = True
- ✓True or False = True
- ✓False or True = True
- ✓False or False = False
There Are No Dumb Questions
"What is the difference between
=and==?"
=is assignment: "put this value in this box."==is comparison: "are these two things equal?" Writingif age = 21:is a common beginner mistake and Python will give you aSyntaxError. Always use==inside conditions."Can I write an if statement on one line?"
Technically yes:
print("adult") if age >= 18 else print("minor"). But do not do this for anything beyond trivial checks. Readable code beats clever code. Use the full multi-line format until you are very comfortable with Python.
Grade Calculator
25 XPFor loops — repeating with a plan
A for loop repeats a block of code once for each item in a sequence. Think of it as going through a checklist: for each item on the list, do this thing.
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# Output:
# I like apple
# I like banana
# I like cherry
The range() function
range() generates a sequence of numbers. It is how you say "do this N times":
# Print numbers 0 through 4
for i in range(5):
print(i)
# Output: 0, 1, 2, 3, 4
# Print numbers 1 through 5
for i in range(1, 6):
print(i)
# Output: 1, 2, 3, 4, 5
# Count by twos
for i in range(0, 10, 2):
print(i)
# Output: 0, 2, 4, 6, 8
Real-world for loop examples
# Calculate a total
prices = [9.99, 24.50, 3.75, 15.00]
total = 0
for price in prices:
total = total + price
print(f"Total: ${total:.2f}") # Total: $53.24
# Find the longest word
words = ["python", "programming", "is", "fun"]
longest = ""
for word in words:
if len(word) > len(longest):
longest = word
print(f"Longest word: {longest}") # Longest word: programming
There Are No Dumb Questions
"What does the variable name in
for x in listmatter?"You can use any name:
for item in list,for banana in list,for x in list. The name is just a temporary label for the current item. Use descriptive names:for student in studentsis much clearer thanfor s in students. The nameiis conventional for number indices."Can I change the list while looping through it?"
Do NOT modify a list while you are iterating over it — this creates unpredictable behavior. If you need to filter items, create a new list instead:
new_list = [x for x in old_list if x > 10]. We will cover this pattern (list comprehensions) in Module 5.
While loops — repeating until a condition changes
A for loop knows in advance how many times it will run. A while loop keeps running until a condition becomes false. Think of it as "keep doing this until I say stop."
# Countdown
count = 5
while count > 0:
print(count)
count = count - 1
print("Blast off!")
# Output: 5, 4, 3, 2, 1, Blast off!
The classic use case: getting valid input from a user.
password = ""
while password != "secret123":
password = input("Enter the password: ")
print("Access granted!")
# DO NOT RUN THIS
while True:
print("This never stops")
Always make sure something inside the loop changes the condition. If your program freezes, press Ctrl+C in the terminal to force-quit it.
Break and continue — loop control
# break — exit the loop immediately
for number in range(100):
if number == 5:
break
print(number)
# Output: 0, 1, 2, 3, 4
# continue — skip this iteration, go to next
for number in range(6):
if number == 3:
continue
print(number)
# Output: 0, 1, 2, 4, 5
FizzBuzz — The Classic
25 XPNested loops and patterns
You can put loops inside loops. Think of a clock: the minute hand completes 60 loops for every single loop of the hour hand.
# Multiplication table (3x3)
for row in range(1, 4):
for col in range(1, 4):
print(f"{row} x {col} = {row * col}", end=" ")
print() # New line after each row
Output:
1 x 1 = 1 1 x 2 = 2 1 x 3 = 3
2 x 1 = 2 2 x 2 = 4 2 x 3 = 6
3 x 1 = 3 3 x 2 = 6 3 x 3 = 9
Putting it all together — a guessing game
Here is a small program that uses everything from this module:
import random
secret = random.randint(1, 20)
attempts = 0
print("I'm thinking of a number between 1 and 20.")
while True:
guess = int(input("Your guess: "))
attempts += 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print(f"You got it in {attempts} attempts!")
break
This uses: variables, type conversion, a while loop, if/elif/else, break, f-strings, and a library import. You already know every piece of this program.
Build the Guessing Game
50 XPKey takeaways
if/elif/elselets your program make decisions — check conditions and take different pathsforloops repeat code for each item in a sequence — "do this for every item"whileloops repeat code until a condition changes — "keep doing this until..."range(n)generates numbers 0 through n-1 — remember, it stops BEFORE nbreakexits a loop immediately;continueskips to the next iteration- Indentation is mandatory in Python — 4 spaces per level, mixing tabs and spaces will crash
=assigns,==compares — the most common beginner bug in all of programming- Avoid infinite loops — make sure the while condition will eventually become false
Knowledge Check
1.What will this code print? ```python x = 15 if x > 20: print('A') elif x > 10: print('B') elif x > 5: print('C') else: print('D') ```
2.What numbers does `range(2, 8)` generate?
3.What is the output of this code? ```python for i in range(5): if i == 3: break print(i) ```
4.Which of the following will cause an infinite loop?