Lesson 5: Conditional Branches & Loops
Evaluating truth tables, if/elif/else routing, for and while loops, break, and continue.
Controlling Execution Flow
A program runs sequentially by default — top to bottom, one line after another. Conditionals and loops are what give your program the power to make decisions and repeat work. Together they turn a static script into dynamic, intelligent software.
Think about it this way: without conditionals, every run of a program produces the identical output, forever. Without loops, you would write the same line a thousand times to repeat a task a thousand times. These two tools are the difference between a calculator and a program.
What You'll Learn in This Lesson
- Route code with
if/elif/else - Understand truthiness — which values count as True or False
- Iterate with
forloops over sequences andrange() - Loop with
whileuntil a condition becomes False - Interrupt loops with
breakandcontinue
Truthiness — What Counts as True?
In Python, every value has a truth value. The following are always falsy:
| Falsy values | |
|---|---|
False |
None |
0 |
0.0 |
"" (empty string) |
[] (empty list) |
{} (empty dict) |
() (empty tuple) |
Everything else is truthy — including negative numbers, the string "0", and empty sets. This lets you write terse checks like if items: (true when the list has anything in it).
Mental model: an empty container or a zero-like value "weighs nothing" and counts as False; anything with content or magnitude counts as True. When you see
if x:, translate it as "if x has anything in it" or "if x is not zero".
Why Truthiness Matters in Real Code
Truthiness is what lets professional code avoid clumsy verbosity:
# Clumsy
if len(items) > 0:
process(items)
# Pythonic — items being non-empty means True
if items:
process(items)
The second version is shorter, reads naturally, and is the style used in virtually all real Python codebases — from Django to PyTorch.
Conditionals — The if / elif / else Chain
A conditional routes the code path based on a boolean expression:
score = 85
if score >= 90:
print("Grade: A+")
elif score >= 75:
print("Grade: B")
elif score >= 60:
print("Grade: C")
else:
print("Grade: F")
Key rules:
- Only ONE branch ever runs — Python checks from top to bottom and takes the first
Truebranch, then skips the rest. elifmeans "else if" and can appear any number of times.elseis optional and catches everything not caught above.- Order matters: check the most specific condition first (90 before 75).
Decision-tree mental model: each
ifis a fork in the road. You walk down the first path whose sign says "True", and you never come back.
Nested Conditionals — Decisions Inside Decisions
An if block can contain another if — useful when a second decision only makes sense after the first:
age = 20
has_id = True
if age >= 18:
if has_id:
print("Welcome in!")
else:
print("Need ID")
else:
print("Too young")
Nesting is fine up to two or three levels — beyond that, restructure with and/or or helper functions to keep code flat and readable.
The for Loop — Iterating Over Sequences
The for loop walks through every item of a sequence:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
You can loop over strings, lists, tuples, dict keys, sets — anything iterable. For a range of numbers, use range():
| Call | Produces |
|---|---|
range(5) |
0, 1, 2, 3, 4 |
range(1, 5) |
1, 2, 3, 4 |
range(1, 10, 2) |
1, 3, 5, 7, 9 (step 2) |
range(5, 0, -1) |
5, 4, 3, 2, 1 (countdown) |
range() has three forms:
| Form | Meaning |
|---|---|
range(stop) |
0 to stop-1 |
range(start, stop) |
start to stop-1 |
range(start, stop, step) |
start to stop-1, jumping by step |
Trace-table tip: write a small table with columns for the loop variable and the output. Step through each iteration — this is exactly what Python does.
Accumulating in a Loop — The Counter Pattern
The single most common loop task is accumulating a total:
total = 0
for n in range(1, 6): # 1 + 2 + 3 + 4 + 5
total += n
print(total) # 15
Trace table for this loop:
| Iteration | n | total before | total after |
|---|---|---|---|
| 1 | 1 | 0 | 1 |
| 2 | 2 | 1 | 3 |
| 3 | 3 | 3 | 6 |
| 4 | 4 | 6 | 10 |
| 5 | 5 | 10 | 15 |
This pattern — initialize before the loop, update inside — powers sums, counts, maximums, and building lists for the rest of the course.
The while Loop — Loop Until False
The while loop repeats as long as its condition is True:
count = 3
while count > 0:
print(count)
count -= 1
print("Blast off!")
Danger: if the condition never becomes False, the loop runs forever (an infinite loop). Always make sure something inside the loop moves the condition toward False.
Choosing between for and while:
| Situation | Use |
|---|---|
| You know how many times (or are iterating a collection) | for |
| You repeat until a condition changes, and the count is unknown | while |
| Example: "ask for password until correct" | while |
| Example: "process every line in a file" | for |
break and continue — Loop Interrupts
| Keyword | Effect | Use case |
|---|---|---|
break |
Exits the loop immediately | "Found it — stop searching" |
continue |
Skips to the next iteration | "Skip this one, keep going" |
for n in range(1, 11):
if n % 3 == 0:
continue # skip multiples of 3
if n == 8:
break # stop at 8
print(n) # 1 2 4 5 7
Mental model:
breakslams on the brakes and leaves the car.continuejumps over one pothole but keeps driving the same route.
Common Mistakes to Avoid
- Mistake:
if score = 90:— Fix: comparison needs==, not=. - Mistake: An infinite
while True:with nobreak— Fix: ensure the condition or a break eventually stops it. - Mistake: Checking
elifconditions in the wrong order (e.g.,>= 60before>= 90) — Fix: order from most to least specific. - Mistake: Forgetting to update the loop variable in a
whileloop — Fix: an unchanged condition means an infinite loop. - Mistake: Indenting the loop body inconsistently — Fix: every statement that belongs to the loop must share the same indent.
Professional Tips & Tricks
- Put the most likely condition first for slightly faster, clearer code.
while True + breakis a clean pattern for menus and input validation loops.range(start, stop, step)gives you full control over for-loop stepping.- Use trace tables on paper for the first few loops — the muscle memory pays off forever.
Key Takeaways
if/elif/elseruns exactly one branch — first True wins.- Truthiness lets you write
if items:instead ofif len(items) > 0:. foriterates over sequences;whilerepeats until False.breakstops a loop;continueskips one iteration.- Always ensure while loops can terminate.
- The accumulate-inside-a-loop pattern is the foundation of nearly every algorithm.
Next up: Loop control in depth — nested loops, the loop else clause, and pass.
# Grade checker script showcasing conditionals and loops
scores = [45, 88, 72, 95, 60, 30]
passing_score = 60
print("Evaluating exam scores:")
for score in scores:
if score >= 90:
print(f"Score {score}: Grade A+ (Excellent!)")
elif score >= passing_score:
print(f"Score {score}: Passing grade")
else:
# Check if failing critically
if score < 40:
print(f"Score {score}: Failed critically (Needs revision)")
continue
print(f"Score {score}: Failed")Lesson Code (Python)
# Grade checker script showcasing conditionals and loops
scores = [45, 88, 72, 95, 60, 30]
passing_score = 60
print("Evaluating exam scores:")
for score in scores:
if score >= 90:
print(f"Score {score}: Grade A+ (Excellent!)")
elif score >= passing_score:
print(f"Score {score}: Passing grade")
else:
# Check if failing critically
if score < 40:
print(f"Score {score}: Failed critically (Needs revision)")
continue
print(f"Score {score}: Failed")Console Output
Evaluating exam scores:
Score 45: Failed
Score 88: Passing grade
Score 72: Passing grade
Score 95: Grade A+ (Excellent!)
Score 60: Passing grade
Score 30: Failed critically (Needs revision)Code Visualization Tips
- Draw a fork-in-the-road diagram for each if/elif/else — only one road is taken per trip.
- Use a trace table with columns: score, condition result, output.
- Step through scores = [45, 88] in Python Tutor to watch the pointer move through the loop.
Professional Tips & Tricks
- Put the most likely condition first for slightly faster, clearer code.
- while True + break is a clean pattern for menus and input validation loops.
- range(start, stop, step) gives you full control over for-loop stepping.
Python Code Judge & Practice Arena
LeetCode StyleRun real Python 3.12 WebAssembly code directly in your browser against automated test suites.
Parity & Divisibility Classifier
Test Your Knowledge
Instant feedbackQuick Check: Lesson 5: Control Flow: If/Else Conditionals & Loops
Up next · Continue learning
Loop Control, Nested Loops & The else Clause
Master break, continue, pass, loop else clauses, and nested loops with trace tables.