Skip to main content

Module 4 - Control Flow

This module covers control flow statements in Python. You'll learn how to make decisions in your code using if/elif/else, match-case, and ternary operators.


1. If Statements

1.1 Basic If Statement

age = 18

if age >= 18:
print("You are an adult")

1.2 If-Else Statement

temperature = 25

if temperature > 30:
print("It's hot outside")
else:
print("It's pleasant weather")

1.3 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}")
Best Practice

Use elif instead of multiple if statements when conditions are mutually exclusive. This improves performance and readability.

1.4 Nested If Statements

age = 25
has_license = True

if age >= 18:
if has_license:
print("You can drive")
else:
print("You need a license")
else:
print("You are too young to drive")

2. Comparison Operators

2.1 Basic Comparisons

OperatorDescriptionExample
==Equal to5 == 5 → True
!=Not equal to5 != 3 → True
>Greater than5 > 3 → True
<Less than3 < 5 → True
>=Greater than or equal5 >= 5 → True
<=Less than or equal3 <= 5 → True
x = 10
y = 20

print(x == y) # False
print(x != y) # True
print(x < y) # True
print(x > y) # False

2.2 Membership Operators

# in operator
fruits = ["apple", "banana", "orange"]
print("apple" in fruits) # True
print("mango" in fruits) # False

# not in operator
print("mango" not in fruits) # True

# Works with strings
text = "Python is awesome"
print("Python" in text) # True

2.3 Identity Operators

a = [1, 2, 3]
b = [1, 2, 3]
c = a

# is operator (checks if same object)
print(a is c) # True
print(a is b) # False

# is not operator
print(a is not b) # True

# == checks value equality
print(a == b) # True
is vs ==
  • == checks if values are equal
  • is checks if objects are the same (same memory location)

3. Logical Operators

3.1 and, or, not

age = 25
has_job = True
has_degree = False

# and operator
if age > 18 and has_job:
print("Eligible for loan")

# or operator
if has_degree or age > 30:
print("Can apply for senior position")

# not operator
if not has_degree:
print("Consider getting a degree")

# Combining operators
if (age > 21 and has_job) or has_degree:
print("Qualified candidate")

3.2 Short-Circuit Evaluation

# and: Returns first falsy value or last value
result = 0 and 5 # 0
result = 5 and 10 # 10
result = None and "hi" # None

# or: Returns first truthy value or last value
result = 0 or 5 # 5
result = 5 or 10 # 5
result = None or False # False

# Practical use
name = input("Name: ") or "Guest" # Default to "Guest" if empty

4. Ternary Operator (Conditional Expression)

4.1 Basic Syntax

# Syntax: value_if_true if condition else value_if_false

age = 20
status = "Adult" if age >= 18 else "Minor"
print(status) # Adult

# Traditional if-else equivalent
if age >= 18:
status = "Adult"
else:
status = "Minor"

4.2 Practical Examples

# Finding max/min
a, b = 10, 20
maximum = a if a > b else b
print(maximum) # 20

# Conditional assignment
score = 85
result = "Pass" if score >= 50 else "Fail"

# Nested ternary (use sparingly)
score = 95
grade = "A" if score >= 90 else ("B" if score >= 80 else "C")

# In function returns
def absolute(num):
return num if num >= 0 else -num

print(absolute(-5)) # 5
Readability

Avoid complex nested ternary operators. Use regular if-elif-else for better readability.


5. Match-Case Statement (Python 3.10+)

5.1 Basic Match Statement

# Traditional if-elif-else
command = "start"

if command == "start":
print("Starting...")
elif command == "stop":
print("Stopping...")
elif command == "pause":
print("Pausing...")
else:
print("Unknown command")

# Using match-case
match command:
case "start":
print("Starting...")
case "stop":
print("Stopping...")
case "pause":
print("Pausing...")
case _:
print("Unknown command")

5.2 Pattern Matching with Multiple Values

status_code = 404

match status_code:
case 200 | 201:
print("Success")
case 400 | 401 | 403:
print("Client error")
case 404:
print("Not found")
case 500 | 502 | 503:
print("Server error")
case _:
print("Unknown status")

5.3 Matching with Conditions (Guards)

point = (0, 5)

match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"On Y-axis at {y}")
case (x, 0):
print(f"On X-axis at {x}")
case (x, y) if x == y:
print(f"On diagonal at ({x}, {y})")
case (x, y):
print(f"Point at ({x}, {y})")

5.4 Matching Data Structures

# Matching lists
command = ["move", 10, 20]

match command:
case ["quit"]:
print("Exiting...")
case ["move", x, y]:
print(f"Moving to ({x}, {y})")
case ["draw", color, shape]:
print(f"Drawing {color} {shape}")
case _:
print("Unknown command")

# Matching dictionaries
user = {"name": "Alice", "role": "admin"}

match user:
case {"role": "admin", "name": name}:
print(f"Admin user: {name}")
case {"role": "user", "name": name}:
print(f"Regular user: {name}")
case _:
print("Unknown user type")
When to Use Match-Case

Use match-case when you have multiple specific values to check. It's more readable than long if-elif chains and supports advanced pattern matching.


6. Truthy and Falsy Values

6.1 Understanding Truthiness

# Falsy values in Python
bool(False) # False
bool(None) # False
bool(0) # False
bool(0.0) # False
bool("") # False (empty string)
bool([]) # False (empty list)
bool({}) # False (empty dict)
bool(()) # False (empty tuple)
bool(set()) # False (empty set)

# Everything else is truthy
bool(True) # True
bool(1) # True
bool("hello") # True
bool([1, 2, 3]) # True

6.2 Using Truthiness in Conditions

# Check if list is empty
numbers = []
if numbers:
print("List has items")
else:
print("List is empty")

# Check if string is empty
name = input("Enter name: ")
if name:
print(f"Hello, {name}")
else:
print("No name entered")

# Check for None
result = None
if result is not None:
print(result)
else:
print("No result")

7. Best Practices

7.1 Prefer Positive Conditions

# Less readable
if not is_invalid:
process_data()

# More readable
if is_valid:
process_data()

7.2 Avoid Redundant Comparisons

# Bad
if x == True:
print("x is true")

# Good
if x:
print("x is truthy")

# Bad
if len(items) > 0:
process(items)

# Good
if items:
process(items)

7.3 Use Early Returns

# Less readable
def process_user(user):
if user is not None:
if user.is_active:
if user.has_permission:
return do_something(user)
else:
return "No permission"
else:
return "User inactive"
else:
return "No user"

# More readable (early returns)
def process_user(user):
if user is None:
return "No user"

if not user.is_active:
return "User inactive"

if not user.has_permission:
return "No permission"

return do_something(user)

8. Summary

ConceptDescriptionExample
if statementExecute code if condition is Trueif x > 0:
elifCheck additional conditionelif x == 0:
elseExecute if all conditions Falseelse:
Ternary operatorInline if-elseresult = a if x else b
match-casePattern matching (3.10+)match value:
ComparisonCompare values==, !=, <, >, <=, >=
LogicalCombine conditionsand, or, not
MembershipCheck containmentin, not in
IdentityCheck same objectis, is not
Key Takeaways
  • Use proper indentation (4 spaces)
  • Prefer elif over multiple if statements
  • Use match-case for complex pattern matching (Python 3.10+)
  • Leverage truthiness for cleaner conditions
  • Use early returns to reduce nesting

9. What's Next?

In Module 5 - Loops, you'll learn:

  • for loops for iteration
  • while loops for conditional repetition
  • break, continue, and else clauses
  • List comprehensions
  • Nested loops and loop optimization

10. Practice Exercises

Exercise 1: Grade Calculator

Write a program that takes a score (0-100) and prints the grade using match-case.

# Your code here

Exercise 2: Triangle Validator

Write a function that checks if three sides can form a valid triangle and determines its type (equilateral, isosceles, scalene).

def validate_triangle(a, b, c):
# Your code here
pass

Exercise 3: Login System

Create a simple login system that checks username and password with appropriate error messages.

def login(username, password):
# Your code here
pass

Exercise 4: Discount Calculator

Calculate discount based on purchase amount using ternary operators:

  • = $100: 20% discount

  • = $50: 10% discount

  • < $50: No discount
# Your code here

Exercise 5: Menu System

Create a menu-driven calculator using match-case for operations: add, subtract, multiply, divide.

# Your code here
Solutions

Try solving these exercises on your own first. Solutions will be provided in the practice section.