Chapter 4: Flow Control
Conditional Statements: if/elif/else
In everyday life, we're constantly making decisions: "If it's raining, bring an umbrella; otherwise, wear a hat." Python's if statement works the same way:
bash
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Your score is {score}, grade is {grade}")bash
Your score is 85, grade is B⚠️ Note: ⚠️ Common mistake: Python uses indentation (usually 4 spaces) to denote code blocks, not curly braces! Inconsistent indentation will cause an
IndentationError. Never mix tabs and spaces.
bash
# Ternary expression (shorthand if-else)
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)bash
Adultfor Loops
A for loop is like a "conveyor belt" — bringing items one by one for processing:
bash
# Iterate over a list
fruits = ["Apple", "Banana", "Orange", "Watermelon"]
for fruit in fruits:
print(f"I like eating {fruit}!")
print("---")
# range() generates number sequences
for i in range(1, 6):
print(f"Iteration {i}")
print("---")
# Iterating with index (enumerate)
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")bash
I like eating Apple!
I like eating Banana!
I like eating Orange!
I like eating Watermelon!
---
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
---
0: Apple
1: Banana
2: Orange
3: Watermelonwhile Loops
bash
# Number guessing game
import random
secret = random.randint(1, 10)
guess = 0
attempts = 0
while guess != secret:
guess = int(input("Guess a number between 1-10: "))
attempts += 1
if guess > secret:
print("Too high!")
elif guess < secret:
print("Too low!")
print(f"🎉 Congratulations! You got it! The answer is {secret}, it took {attempts} tries.")bash
Guess a number between 1-10: 5
Too high!
Guess a number between 1-10: 3
Too low!
Guess a number between 1-10: 4
🎉 Congratulations! You got it! The answer is 4, it took 3 tries.break, continue, and for...else
bash
# break: immediately exit the loop
print("break example: stop after finding the first even number")
numbers = [1, 3, 5, 8, 9, 10]
for n in numbers:
if n % 2 == 0:
print(f"Found even number: {n}")
break
print(f" Checking {n}...")
print("\ncontinue example: skip even numbers")
for n in range(1, 8):
if n % 2 == 0:
continue
print(f"Odd: {n}")
print("\nfor...else example: check if all numbers are positive")
test_list = [1, 2, 3, 4, 5]
for n in test_list:
if n < 0:
print("Found a negative number!")
break
else:
# Executes when loop completes normally (no break)
print("All numbers are positive ✅")bash
break example: stop after finding the first even number
Checking 1...
Checking 3...
Checking 5...
Found even number: 8
continue example: skip even numbers
Odd: 1
Odd: 3
Odd: 5
Odd: 7
for...else example: check if all numbers are positive
All numbers are positive ✅📝 Note: 📝 Fun fact:
for...elseis a Python-unique syntax. Theelseblock only executes when the loop completes normally (without hittingbreak). Commonly used in search scenarios: "If we searched everything and didn't find it, execute the else block."