Control Flow
Control flow simply decides which line of code runs, and when it runs. It helps your program:
- make decisions based on conditions
- repeat tasks again and again without writing the same code many times
- stop or skip certain steps whenever needed
- handle different situations depending on what’s happening
if, elif, else Statements
Section titled “if, elif, else Statements”These statements help you make decisions in your code and control what happens next.
if-> checks a condition (runs the code inside if it is True)elif-> checks one more condition, but only if the first one was falseelse-> runs only if none of the above conditions were true
Order matters here: elif and else parts are optional, and you can add as many elif blocks as you want, one after another.
x = 10
if x > 10: print("Greater than 10")elif x == 10: print("Equal to 10")else: print("Less than 10")Good Habit: Use elif when you have multiple conditions to check, instead of writing if statements inside other if statements. It’s much easier to read this way.
Flow of execution
Section titled “Flow of execution”Ternary Operator
Section titled “Ternary Operator”This is just a short and quick way to write a simple if-else statement in just one line. It’s also called a conditional expression.
age = 18status = "Adult" if age >= 18 else "Minor"print(status) # Output: AdultHow it’s written: value_if_true if condition else value_if_false
When to Use It:
- When you want to assign a value based on a simple condition
- When you want to set a default value
- When you want to avoid writing long if-else blocks for small things
Watch Out: Try not to put one ternary operator inside another. It makes the code confusing and hard to read.
match-case Statement
Section titled “match-case Statement”This lets you compare one value against several patterns to find a match. This is only available in Python 3.10 and above.
def check(value): match value: case 1: return "One" case 2: return "Two" case _: return "Other"
print(check(2)) # Output: TwoMain Points:
case pattern:-> matches one specific value_-> this is the default case (it matches anything that didn’t match before)- This is easier to read than writing a long chain of if-elif-else statements
- It also runs faster when you have a lot of conditions to check
More Advanced Patterns:
match point: case (0, 0): print("Origin") case (0, y): print(f"On Y axis: {y}") case (x, 0): print(f"On X axis: {x}") case _: print("General point")Flow idea
Section titled “Flow idea”for Loops
Section titled “for Loops”A for loop goes through each item in a sequence, one at a time. It’s the loop you’ll use the most in Python.
for i in range(3): print(i)Output:
012Going Through a Collection:
names = ["A", "B", "C"]
for name in names: print(name)Good Habits to Follow:
- Use a
forloop instead of awhileloop whenever you’re going through a sequence - Use
enumerate()when you need both the position (index) and the value together - Use
zip()when you need to go through more than one sequence at the same time - Use clear and meaningful names for your variables: write
for user in users:instead offor u in users:
How it works
Section titled “How it works”while Loops
Section titled “while Loops”A while loop keeps running again and again, until the condition turns false.
count = 0
while count < 3: print(count) count += 1Main Difference Between for and while:
for-> use this when you already know what you’re looping throughwhile-> use this when you want to keep looping until something becomes false- Be careful, because if the condition never becomes false, the loop will run forever
Common Ways It’s Used:
# Input validationwhile True: user_input = input("Enter a number: ") if user_input.isdigit(): break
# Event loop simulationrunning = Truewhile running: handle_events() update() render()break, continue, pass and else in Loops
Section titled “break, continue, pass and else in Loops”These statements let you control how your loop behaves in more detailed situations.
This stops the loop right away and exits it completely.
for i in range(5): if i == 3: break # Exits loop when i equals 3 print(i)Output: 0 1 2
continue
Section titled “continue”This skips the current round of the loop and moves straight to the next one.
for i in range(5): if i == 2: continue # Skips i=2 print(i)Output: 0 1 3 4
This does absolutely nothing when it runs. It’s mainly used as a placeholder, just to keep the code valid.
for i in range(5): if i == 2: pass # Placeholder, does nothing
if i == 3: pass # Also valid print(i)else in Loops
Section titled “else in Loops”This part only runs if the loop finishes completely on its own without hitting a break.
for i in range(3): print(i)else: print("Loop finished normally")
# Search examplefor user in users: if user.id == target_id: print("User found") breakelse: print("User not found")Flow with break
Section titled “Flow with break”range Function
Section titled “range Function”range() is used to create a sequence of numbers easily and efficiently. You’ll see it used in loops all the time.
for i in range(5): print(i) # 0, 1, 2, 3, 4Three Ways to Use It:
-
range(end)-> starts from 0 and goes up to end-1range(5) # 0, 1, 2, 3, 4 -
range(start, end)-> starts from start and goes up to end-1range(1, 6) # 1, 2, 3, 4, 5 -
range(start, end, step)-> starts from start, goes up to end-1, and jumps ahead by step each timerange(0, 10, 2) # 0, 2, 4, 6, 8range(10, 0, -2) # 10, 8, 6, 4, 2 (reverse)
Good Things to Know:
range()doesn’t actually create the full list right away, it creates the numbers only when needed, which saves memory- If you need an actual list, you can convert it like this:
list(range(5)) - You can also use a negative step number to count backwards
enumerate Function
Section titled “enumerate Function”This adds a position number (index) to each item while you’re looping through it. It’s really useful when you need both the position and the value at the same time.
items = ["a", "b", "c"]
for index, value in enumerate(items): print(index, value)Output:
0 a1 b2 cChanging the Starting Number:
for index, value in enumerate(items, start=1): print(index, value)Output:
1 a2 b3 cA Real-Life Example:
tasks = ["buy milk", "pay bills", "exercise"]
for num, task in enumerate(tasks, 1): print(f"{num}. {task}")# Output:# 1. buy milk# 2. pay bills# 3. exercisezip Function
Section titled “zip Function”This joins multiple sequences together, matching up items based on their position. It’s great when you want to loop through more than one list at the same time.
names = ["A", "B"]scores = [90, 80]
for name, score in zip(names, scores): print(name, score)Output:
A 90B 80Things to Remember:
- It stops as soon as the shortest sequence runs out of items
- It works with any kind of sequence, like lists, tuples, strings, and so on
names = ["A", "B", "C"]scores = [90, 80] # Only 2 elements
for name, score in zip(names, scores): print(name, score)# Output:# A 90# B 80# C is skipped because no corresponding scoreUseful Examples:
# Merge multiple listslist1 = [1, 2, 3]list2 = ['a', 'b', 'c']combined = list(zip(list1, list2))# Output: [(1, 'a'), (2, 'b'), (3, 'c')]
# Process related data in parallelstudents = ["Alice", "Bob", "Charlie"]gpa = [3.8, 3.5, 3.9]for student, grade in zip(students, gpa): print(f"{student}: {grade}")