[practice]Python Basics
Functions & Comprehensions
# theory
Functions are reusable blocks. def, then params, return value:
def greet(name):
return f"hi {name}"
greet("Alice") # "hi Alice"
Defaults turn params optional. Pass by keyword to skip ahead:
def total(price, qty, tax_rate=0.08):
subtotal = price * qty
return subtotal + subtotal * tax_rate
total(10, 5) # uses default
total(10, 5, tax_rate=0.10) # override
List comprehensions replace the for/append loop. These two do the same thing, but the second one is what experienced Python looks like:
squares = []
for x in range(5):
squares.append(x ** 2)
squares = [x ** 2 for x in range(5)]
Add a condition to filter:
evens = [x for x in range(10) if x % 2 == 0]
passing = [s for s in scores if s >= 70]
Dict comprehensions work the same way:
grade_book = {name: score for name, score in zip(names, scores)}
doubled = {k: v * 2 for k, v in prices.items()}# examples [3]
Parameters can have default values
Various patterns for list comprehensions
Build dictionaries with comprehension syntax
# challenges [2]
# project
# project-challenge
thread: SF Permits Analysis · reward: 50 xp
# brief
Build a reusable function to filter permits by any status. The dashboard will call this function to show different views like 'active permits' or 'cancelled permits'.
# task