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. In Module 2, you learned to store data in variables. Now you will learn to make decisions based on that data. 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")✗ and (both must be true)
- ✗True and True = True
- ✗True and False = False
- ✗False and True = False
- ✗False and False = False
✓ or (at least one must be true)
- ✓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 XPWrite a program that converts a numerical score to a letter grade: - 90-100: A - 80-89: B - 70-79: C - 60-69: D - Below 60: F ```python score = int(input("Enter your score: ")) # Write your if/elif/else chain here ``` Test with scores: 95, 85, 72, 63, 45. Does each one give the correct grade? _Hint: Start from the highest condition and work down. Check `score >= 90` first, then `score >= 80`, etc. The order matters because Python stops at the first true condition._
Sign in to earn 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 cherryThe 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, 8Real-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: programmingThere 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, 5FizzBuzz — The Classic
25 XPWrite a program that prints numbers 1 to 30, but: - For multiples of 3, print "Fizz" instead of the number - For multiples of 5, print "Buzz" instead of the number - For multiples of both 3 AND 5, print "FizzBuzz" Expected first 15 lines: ``` 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz ``` _Hint: Use `%` (modulo) to check divisibility. `number % 3 == 0` means "number is divisible by 3." Check the combined condition (both 3 AND 5) FIRST — order of if/elif matters._
Sign in to earn XP<classifychallenge xp="25" title="For Loop or While Loop?" items={["Print every item in a shopping list","Keep asking for a password until it matches","Count from 1 to 100","Read each line from a file","Wait for the user to type 'quit'","Calculate the total of 5 test scores"]} options={["for loop","while loop"]} hint="Use a for loop when you know in advance how many times to repeat (a list, a range, a file). Use a while loop when you keep going until a condition changes (password match, user quits). If you can count the iterations before starting, it is a for loop.">
Nested 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 rowOutput:
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!")
breakThis 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 XPType in the guessing game code above and run it. Then extend it with these features: 1. Limit the player to 5 guesses. After 5 wrong guesses, reveal the answer. 2. After the game ends, ask "Play again? (y/n)" and restart if they say yes. _Hint: For the guess limit, add a condition: `if attempts >= 5`. For replay, wrap the whole game in another `while True` loop that breaks when the user says "n"._
Sign in to earn XPBack to the thermostat
The thermostat you met at the start of this module checks a condition and takes a different action depending on the result. That is exactly what if/elif/else does. The thermostat also repeats — it checks the temperature over and over, forever. That is a while True loop with a sensor reading. Every smart device in your home — your thermostat, your smoke detector, your washing machine — runs on the same control flow patterns you just learned.
You now have the three pillars of programming: data (Module 2), decisions (if/else), and repetition (loops). Everything else is built on top of these.
Next up: The guessing game you just built works, but all the code lives in one place. In the next module, you will learn functions — how to package code into reusable recipes. You will turn that password validator, that grade calculator, and that guessing game into clean, organized functions you can call whenever you need them.
Key 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?
Want to go deeper?
💻 Software Engineering Master Class
The complete software engineering program — from your first line of code to landing your first job.
View the full program