Control Flow & Functions
Master loops, conditionals, and writing reusable code with Python functions.
Conditional Logic
Python uses if, elif, and else for decision making.
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
Loops: iteration made easy
Use for loops to iterate over any iterable (list, string, range) and while loops for condition-based iteration.
# Iterate over a list
for x in [1, 2, 3]:
print(x)
# Iterate using range
for i in range(5):
print(i) # 0 to 4
for x in [1, 2, 3]:
print(x)
# Iterate using range
for i in range(5):
print(i) # 0 to 4
Functions: building blocks
Functions let you encapsulate code for reuse. Python supports default arguments and keyword arguments.
def calculate_total(price, tax=0.05):
return price * (1 + tax)
total1 = calculate_total(100)
total2 = calculate_total(100, tax=0.10)
return price * (1 + tax)
total1 = calculate_total(100)
total2 = calculate_total(100, tax=0.10)
List Comprehensions
A concise way to create lists based on existing lists.
nums = [1, 2, 3, 4]
squares = [x**2 for x in nums if x > 2]
# Result: [9, 16]
squares = [x**2 for x in nums if x > 2]
# Result: [9, 16]
โ Practice (15 minutes)
- Write a function that takes a number and returns
Trueif it's even,Falseotherwise. - Create a list of names and use a
forloop to print only names longer than 5 characters. - Use a list comprehension to create a list of numbers from 1 to 20 that are divisible by 3.