Control Flow
Control flow determines which lines of your program run, in what order, and under what conditions. Without control flow, every program would run top to bottom with no decisions and no repetition.
Why This Chapter Matters
Almost every real-world program needs to make decisions. Login systems check credentials. Games check scores. Forms validate inputs. Control flow is how code reacts to data.
- you will write programs that respond differently based on conditions
- you will understand
if,elif,else, and how Python evaluates conditions - you will use
forandwhileloops to repeat actions - you will know how to exit loops and skip iterations
Conditional Statements
The if Statement
The if statement runs a block of code only when its condition is True.
temperature = 35
if temperature > 30:
print("It is a hot day.")
The colon : ends the condition line, and the indented block is the body.
if / else
else provides a fallback when the if condition is False.
score = 55
if score >= 60:
print("You passed!")
else:
print("You need to study more.")
if / elif / else
elif (else if) checks additional conditions when the first if fails.
score = 82
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
Only the first matching condition runs. Once matched, Python skips the rest.
Order Matters
# Bad — score 95 prints "Passed" and never reaches "Excellent"
if score >= 60:
print("Passed")
elif score >= 90:
print("Excellent") # unreachable!
Always check the most specific condition first.
Comparison Operators
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
print(5 == 5) # True
print(5 != 3) # True
print(10 > 10) # False
print(10 >= 10) # True
Logical Operators
Combine conditions using and, or, not.
and — Both Must Be True
has_ticket = True
has_id = True
if has_ticket and has_id:
print("Welcome to the concert!")
or — At Least One Must Be True
is_admin = False
is_moderator = True
if is_admin or is_moderator:
print("Access granted")
not — Reverse the Truth
is_banned = False
if not is_banned:
print("User can log in")
Truthiness in Conditions
Python does not require conditions to be strictly True or False. Any value is evaluated for truthiness.
username = ""
if username:
print("Username provided")
else:
print("Username is empty") # runs because empty string is falsy
The Ternary (Inline) Expression
Python supports a one-line conditional expression:
status = "adult" if age >= 18 else "minor"
print(status)
This is clean for simple cases. Avoid nesting ternaries — they become hard to read.
for Loops
A for loop iterates over a sequence of values.
Iterating a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Iterating a String
for char in "Python":
print(char)
The range() Function
range() generates a sequence of numbers.
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for i in range(1, 6):
print(i) # 1, 2, 3, 4, 5
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
Iterating with Index (enumerate())
names = ["Asha", "Leo", "Mina"]
for index, name in enumerate(names):
print(f"{index}: {name}")
while Loops
A while loop keeps running as long as its condition is True.
count = 0
while count < 5:
print(count)
count += 1
Always make sure the loop variable changes, or you will create an infinite loop.
break, continue, and else on Loops
break — Exit the Loop Immediately
for number in range(10):
if number == 5:
break
print(number) # prints 0, 1, 2, 3, 4
continue — Skip to the Next Iteration
for number in range(10):
if number % 2 == 0:
continue
print(number) # prints only odd numbers: 1, 3, 5, 7, 9
else on a Loop
The else block runs only when the loop completes without hitting a break:
for number in range(5):
if number == 10:
break
else:
print("Loop finished without break") # this runs
Nested Loops
Loops can be placed inside other loops.
for row in range(1, 4):
for col in range(1, 4):
print(f"({row}, {col})", end=" ")
print()
Output:
(1, 1) (1, 2) (1, 3)
(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)
Real-World Examples
Grade Checker
def grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
else:
return "F"
print(grade(85)) # B
Password Validator
password = input("Enter password: ")
if len(password) < 8:
print("Too short")
elif not any(c.isdigit() for c in password):
print("Must contain a number")
else:
print("Password is valid")
Number Guessing Loop
secret = 42
guess = 0
while guess != secret:
guess = int(input("Guess: "))
if guess < secret:
print("Higher!")
elif guess > secret:
print("Lower!")
print("Correct!")
Common Mistakes
- forgetting the colon
:afterif,elif,else,for,while - incorrect indentation inside blocks
- using
=(assignment) instead of==(comparison) in conditions - creating infinite
whileloops by forgetting to update the condition variable - off-by-one errors with
range()(remember:range(n)goes from 0 to n-1)
Mini Exercises
- Write an
if/elif/elsechain that categorizes a temperature as cold, warm, or hot. - Use a
forloop to print the multiplication table for 7. - Write a
whileloop that keeps asking for input until the user types "quit". - Use
breakto find the first number in a list that is divisible by 7. - Use
continueto print all numbers from 1~20 that are NOT divisible by 3.
Review Questions
- What is the difference between
if/elif/elseand multiple separateifstatements? - Why does the order of
elifconditions matter? - What is the difference between
breakandcontinuein a loop? - When does the
elseblock on aforloop run? - What is the output of
range(2, 10, 3)?
Reference Checklist
- I can write
if,elif, andelsechains correctly - I understand all comparison and logical operators
- I can use
forloops with lists, strings, andrange() - I can use
enumerate()to loop with an index - I can use
whileloops and know how to avoid infinite loops - I know when to use
break,continue, andelseon loops