Control Flow π¶
What You'll Learn
- β
How Python makes decisions with
if,elif,else - β Ternary (conditional) expressions
- β
matchstatement (Python 3.10+) - β
forandwhileloops with real examples - β
break,continue,pass, andelseon loops - β Nested conditions and common mistakes to avoid
π Introduction¶
Control flow is how a program decides what to do next. By default, Python executes code line by line from top to bottom. Control flow statements let you branch, repeat, and skip code based on conditions.
New to Python?
Start with Basics β Complexity Analysis β Data Structures β Algorithms before jumping into practice problems.
Already know Python?
Jump straight to Data Structures or Algorithms depending on what you're revising.
Keep in mind
Every topic includes real code examples, memory diagrams, and practical use cases β read them carefully, don't just skim the code.
π Conditionals¶
1οΈβ£ if / elif / else¶
The most fundamental decision-making structure in Python.
Real-Life Example
- If it's raining β take an umbrella
- Elif it's cloudy β maybe take one
- Else β enjoy the sun βοΈ
Basic Syntax
age = 20
if age < 13:
print("Child")
elif age < 18:
print("Teenager")
elif age < 60:
print("Adult")
else:
print("Senior")
Output:
How Python Evaluates It
age = 20
if age < 13 β False β skip
elif age < 18 β False β skip
elif age < 60 β True β execute β print "Adult"
else β skipped (a branch already ran)
Practical Example: Grade System
marks = int(input("Enter your marks (0-100): "))
if marks >= 90:
grade = "A"
remark = "π Excellent!"
elif marks >= 80:
grade = "B"
remark = "π Good!"
elif marks >= 70:
grade = "C"
remark = "π Average"
elif marks >= 60:
grade = "D"
remark = "π Below Average"
elif marks >= 0:
grade = "F"
remark = "π Fail"
else:
grade = "?"
remark = "β Invalid marks"
print(f"Grade: {grade} β {remark}")
Output:
Nested if
num = 15
if num > 0:
print("Positive")
if num % 2 == 0:
print("and Even")
else:
print("and Odd")
else:
print("Non-positive")
Output:
Indentation is Everything
# β
Correct
if True:
print("inside if")
# β IndentationError
if True:
print("no indent") # IndentationError!
{} braces. Getting this wrong crashes your program.
Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to | x == 5 |
!= |
Not equal | x != 5 |
> |
Greater than | x > 5 |
< |
Less than | x < 5 |
>= |
Greater or equal | x >= 5 |
<= |
Less or equal | x <= 5 |
2οΈβ£ Logical Operators (and, or, not)¶
Combine multiple conditions into one.
age = 25
has_id = True
# and β both must be True
if age >= 18 and has_id:
print("Entry allowed β
")
# or β at least one must be True
is_weekend = False
is_holiday = True
if is_weekend or is_holiday:
print("Day off! π")
# not β flips True/False
is_raining = False
if not is_raining:
print("Go for a walk πΆ")
Output:
Truth Table
AND: OR: NOT:
βββββββββ¬ββββββββ¬ββββ βββββββββ¬ββββββββ¬ββββ βββββββββ¬ββββββββ
β A β B βAβ§Bβ β A β B βAβ¨Bβ β A β Β¬A β
βββββββββΌββββββββΌββββ€ βββββββββΌββββββββΌββββ€ βββββββββΌββββββββ€
β True β True β T β β True β True β T β β True β False β
β True β False β F β β True β False β T β β False β True β
β False β True β F β β False β True β T β βββββββββ΄ββββββββ
β False β False β F β β False β False β F β
βββββββββ΄ββββββββ΄ββββ βββββββββ΄ββββββββ΄ββββ
Short-Circuit Evaluation
# 'and' stops at first False
x = 0
if x != 0 and 10 / x > 1: # safe! β stops at x != 0
print("big")
# 'or' stops at first True
name = "Alice"
if name or input("Enter name: "): # stops at name β no input needed
print(f"Hello, {name}")
3οΈβ£ Ternary Expression¶
A one-line if-else for simple conditions.
# Syntax: value_if_true if condition else value_if_false
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
# Nested ternary (use sparingly!)
score = 75
grade = "A" if score >= 90 else "B" if score >= 80 else "C"
print(grade)
Output:
Don't Overuse Ternary
Keep ternary expressions simple. If you need more than one else, use a regular if-elif-else for readability.
4οΈβ£ match Statement (Python 3.10+)¶
Python's version of switch-case β cleaner than long elif chains.
command = "quit"
match command:
case "start":
print("Starting the engine π")
case "stop":
print("Stopping... π")
case "pause":
print("Paused βΈοΈ")
case "quit" | "exit":
print("Goodbye! π")
case _:
print(f"Unknown command: {command}")
Output:
Match with Values
point = (0, 1)
match point:
case (0, 0):
print("Origin")
case (x, 0):
print(f"On X-axis at {x}")
case (0, y):
print(f"On Y-axis at {y}")
case (x, y):
print(f"Point at ({x}, {y})")
Output:
match vs if-elif
match |
if-elif |
|
|---|---|---|
| Python version | 3.10+ only | All versions |
| Pattern matching | β Powerful | β Basic |
| Readability | β Cleaner | Verbose for many cases |
| Use case | Multiple exact values | Complex conditions |
π Loops¶
5οΈβ£ for Loop¶
Iterates over any iterable β list, string, range, dict, etc.
Real-Life Example
- For each student in the class β print their name
- For each item in cart β calculate total price
Basic Syntax
Output:
range() Function
enumerate() β Index + Value
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Start index from 1
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")
Output:
Iterating Over Strings
Output:
Iterating Over Dictionaries
student = {"name": "Alice", "age": 20, "gpa": 3.8}
for key in student:
print(key)
for key, value in student.items():
print(f"{key}: {value}")
Output:
Nested for Loops
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i}Γ{j}={i*j}", end=" ")
print()
Output:
Memory Visualization
for fruit in ["apple", "banana", "cherry"]:
Iteration 1: fruit β "apple" β body executes
Iteration 2: fruit β "banana" β body executes
Iteration 3: fruit β "cherry" β body executes
(no more items) β loop ends
6οΈβ£ while Loop¶
Repeats as long as a condition is True. Use when you don't know how many times to loop.
Real-Life Example
- While the ATM has balance β allow withdrawals
- While user hasn't guessed correctly β keep asking
Basic Syntax
Output:
Practical Example: Number Guessing Game
import random
secret = random.randint(1, 10)
attempts = 0
while True:
guess = int(input("Guess (1-10): "))
attempts += 1
if guess < secret:
print("Too low! π")
elif guess > secret:
print("Too high! π")
else:
print(f"π Correct! Got it in {attempts} attempts!")
break
Output:
Guess (1-10): 5
Too low! π
Guess (1-10): 8
Too high! π
Guess (1-10): 6
π Correct! Got it in 3 attempts!
Infinite Loop
ποΈ Loop Control Statements¶
7οΈβ£ break¶
Exits the loop immediately, regardless of the condition.
numbers = [1, 3, 7, 2, 9, 4, 6]
for num in numbers:
if num == 2:
print(f"Found 2! Stopping.")
break
print(num)
Output:
Memory Visualization
for num in [1, 3, 7, 2, 9, 4, 6]:
num=1 β print(1)
num=3 β print(3)
num=7 β print(7)
num=2 β condition True β BREAK βββββββββββββββββββ
num=9 β never reached β
num=4 β never reached β
num=6 β never reached β
βΌ
continues after loop
8οΈβ£ continue¶
Skips the current iteration and jumps to the next one.
Output:
Practical: Skip Invalid Input
data = [10, -5, 20, -3, 15, 0, 8]
total = 0
for num in data:
if num <= 0:
continue # skip non-positive
total += num
print(f"Sum of positives: {total}")
Output:
9οΈβ£ pass¶
Does absolutely nothing β a placeholder for empty blocks.
# Placeholder for future code
for i in range(5):
pass # TODO: add logic later
# Empty function body
def my_function():
pass
# Empty class
class MyClass:
pass
print("No errors! β
")
Output:
Why pass?
Python doesn't allow empty blocks β an if, for, def, or class with no body causes a SyntaxError. pass is the fix.
π else on Loops¶
Python has a unique feature β else on loops. The else block runs only if the loop completed without break.
# Search for a number
numbers = [1, 3, 5, 7, 9]
target = 6
for num in numbers:
if num == target:
print(f"Found {target}!")
break
else:
print(f"{target} not found in list.")
Output:
With break (else skipped)
numbers = [1, 3, 5, 6, 9]
target = 6
for num in numbers:
if num == target:
print(f"Found {target}!")
break
else:
print(f"{target} not found.") # skipped because break ran
Output:
while-else
attempts = 0
max_attempts = 3
while attempts < max_attempts:
password = input("Enter password: ")
if password == "secret123":
print("β
Access granted!")
break
attempts += 1
else:
print("β Too many failed attempts. Locked out!")
Loop else β When to Use
Perfect for search loops where you want to know if something was found or not, without using a flag variable.
β Quick Reference Summary¶
| Statement | Purpose | Runs when |
|---|---|---|
if |
Check condition | condition is True |
elif |
Alternative condition | previous was False, this is True |
else |
Fallback | all above were False |
match |
Pattern matching (3.10+) | value matches a case |
for |
Iterate over iterable | each item in sequence |
while |
Repeat while condition | condition is True |
break |
Exit loop early | immediately on execution |
continue |
Skip current iteration | immediately on execution |
pass |
Do nothing (placeholder) | immediately, no effect |
for-else |
Run after loop | loop finished without break |