Docs
control flow
03 - Control Flow
📌 What You'll Learn
- •Conditional statements (if, elif, else)
- •Comparison and logical operators in conditions
- •Loops (for, while)
- •Loop control (break, continue, pass)
- •List comprehensions
- •Match-case statements (Python 3.10+)
🔀 Conditional Statements
Conditional statements allow your program to make decisions and execute different code based on conditions.
if Statement
age = 18
if age >= 18:
print("You are an adult")
if-else Statement
age = 15
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
if-elif-else Statement
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 grade is: {grade}")
Nested if Statements
age = 25
has_license = True
if age >= 18:
if has_license:
print("You can drive")
else:
print("Get a license first")
else:
print("Too young to drive")
🎯 Conditions and Operators
Comparison Operators in Conditions
x = 10
if x == 10: # Equal
print("x is 10")
if x != 5: # Not equal
print("x is not 5")
if x > 5: # Greater than
print("x is greater than 5")
if x >= 10: # Greater or equal
print("x is 10 or more")
Logical Operators
age = 25
has_id = True
# AND - both conditions must be True
if age >= 18 and has_id:
print("Can enter")
# OR - at least one condition must be True
if age < 18 or not has_id:
print("Cannot enter")
# NOT - inverts the condition
if not (age < 18):
print("Adult")
Combining Multiple Conditions
score = 85
attendance = 90
if score >= 80 and attendance >= 80:
print("Excellent student")
elif score >= 60 or attendance >= 90:
print("Good student")
else:
print("Needs improvement")
Membership Operators
fruits = ["apple", "banana", "cherry"]
if "apple" in fruits:
print("Apple is available")
if "mango" not in fruits:
print("Mango is not available")
Identity Operators
a = [1, 2, 3]
b = a
c = [1, 2, 3]
if a is b: # Same object in memory
print("a and b are the same object")
if a is not c: # Different objects
print("a and c are different objects")
📐 Ternary Operator (Conditional Expression)
A one-line way to write simple if-else statements.
# Syntax: value_if_true if condition else value_if_false
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult
# Multiple conditions
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C"
print(grade) # B
# In function calls
x = 5
print("positive" if x > 0 else "zero or negative")
🔄 Truthy and Falsy Values
In Python, values have a boolean context (truthy or falsy).
# Falsy values (evaluate to False):
# - False
# - None
# - 0 (integer zero)
# - 0.0 (float zero)
# - "" (empty string)
# - [] (empty list)
# - {} (empty dict)
# - () (empty tuple)
# - set() (empty set)
# Examples:
if []:
print("This won't print") # Empty list is falsy
if [1, 2, 3]:
print("This will print") # Non-empty list is truthy
# Common pattern: check if list has items
items = []
if items:
print("Has items")
else:
print("Empty list")
# Check for None
value = None
if value is None:
print("No value provided")
🔁 For Loop
The for loop iterates over a sequence (list, tuple, string, range, etc.).
Basic for Loop
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterate over a string
for char in "Python":
print(char)
# Iterate over a range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8 (step of 2)
print(i)
for i in range(10, 0, -1): # 10, 9, 8... 1 (countdown)
print(i)
enumerate() - Get Index and Value
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: cherry
# Start from different index
for index, fruit in enumerate(fruits, start=1):
print(f"{index}: {fruit}")
zip() - Iterate Multiple Sequences
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# With three lists
scores = [90, 85, 95]
for name, age, score in zip(names, ages, scores):
print(f"{name}, {age}, scored {score}")
Nested for Loops
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
print() # Empty line between tables
🔄 While Loop
The while loop repeats as long as a condition is True.
Basic while Loop
count = 0
while count < 5:
print(count)
count += 1
# Output: 0, 1, 2, 3, 4
while with User Input
# Keep asking until valid input
while True:
answer = input("Enter 'quit' to exit: ")
if answer.lower() == 'quit':
break
print(f"You entered: {answer}")
while with else
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop completed normally")
# The else block runs when the loop completes without break
Avoiding Infinite Loops
# BAD - Infinite loop!
# while True:
# print("Forever...")
# GOOD - Has exit condition
count = 0
while count < 10:
print(count)
count += 1 # Don't forget to update!
🛑 Loop Control Statements
break - Exit the Loop
# Stop when we find what we're looking for
for num in range(10):
if num == 5:
print("Found 5!")
break
print(num)
# Output: 0, 1, 2, 3, 4, Found 5!
continue - Skip to Next Iteration
# Skip odd numbers
for num in range(10):
if num % 2 != 0:
continue
print(num)
# Output: 0, 2, 4, 6, 8
pass - Do Nothing (Placeholder)
# Placeholder for future code
for num in range(5):
if num == 3:
pass # TODO: handle this case later
else:
print(num)
# Empty function placeholder
def my_function():
pass # Will implement later
else with Loops
# else runs if loop completes WITHOUT break
for num in range(5):
if num == 10: # Never true
break
else:
print("Loop completed without finding 10")
# else does NOT run if break is executed
for num in range(5):
if num == 3:
break
else:
print("This won't print") # break was executed
📋 List Comprehensions
A concise way to create lists based on existing sequences.
Basic Syntax
# [expression for item in iterable]
# Traditional way
squares = []
for x in range(5):
squares.append(x ** 2)
# List comprehension
squares = [x ** 2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
With Condition
# [expression for item in iterable if condition]
# Even numbers only
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
# Filter and transform
words = ["hello", "world", "python", "hi"]
long_words_upper = [w.upper() for w in words if len(w) > 3]
print(long_words_upper) # ['HELLO', 'WORLD', 'PYTHON']
With if-else
# [expr_if_true if condition else expr_if_false for item in iterable]
numbers = [1, 2, 3, 4, 5]
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels) # ['odd', 'even', 'odd', 'even', 'odd']
Nested Comprehensions
# Flatten a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Create a 2D list
grid = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(grid) # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
📦 Dictionary and Set Comprehensions
Dictionary Comprehension
# {key: value for item in iterable}
# Create dict from two lists
names = ["a", "b", "c"]
values = [1, 2, 3]
my_dict = {k: v for k, v in zip(names, values)}
print(my_dict) # {'a': 1, 'b': 2, 'c': 3}
# Square numbers dict
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Filter
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares) # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Set Comprehension
# {expression for item in iterable}
# Unique squared values
nums = [1, 2, 2, 3, 3, 3]
unique_squares = {x**2 for x in nums}
print(unique_squares) # {1, 4, 9}
🎭 Match-Case (Python 3.10+)
Pattern matching similar to switch-case in other languages.
Basic Match
status = 404
match status:
case 200:
print("OK")
case 404:
print("Not Found")
case 500:
print("Server Error")
case _:
print("Unknown status") # _ is the default case
Match with Patterns
# Match with multiple values
def get_day_type(day):
match day.lower():
case "saturday" | "sunday":
return "Weekend"
case "monday" | "tuesday" | "wednesday" | "thursday" | "friday":
return "Weekday"
case _:
return "Invalid day"
# Match with guards
def classify_number(n):
match n:
case n if n < 0:
return "negative"
case 0:
return "zero"
case n if n > 0:
return "positive"
# Match with sequences
def analyze_point(point):
match point:
case (0, 0):
return "Origin"
case (0, y):
return f"On Y-axis at y={y}"
case (x, 0):
return f"On X-axis at x={x}"
case (x, y):
return f"Point at ({x}, {y})"
📝 Summary
| Concept | Syntax | Description |
|---|---|---|
| if | if condition: | Execute if condition is True |
| elif | elif condition: | Check another condition |
| else | else: | Execute if all conditions False |
| for | for item in sequence: | Iterate over sequence |
| while | while condition: | Loop while condition is True |
| break | break | Exit the loop |
| continue | continue | Skip to next iteration |
| pass | pass | Do nothing placeholder |
| Ternary | a if cond else b | One-line conditional |
| List comp | [x for x in list] | Create list from iterable |
🎯 Next Steps
After mastering control flow, proceed to 04_data_structures to learn about lists, tuples, dicts, and sets!