pyodide: loading…

[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]

# example 01 · function with default parameter

Parameters can have default values

1
2
3
4
5
6
🐍
Loading PythonSetting up pandas & numpy...
# example 02 · list comprehension examples

Various patterns for list comprehensions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
🐍
Loading PythonSetting up pandas & numpy...
# example 03 · dictionary comprehension

Build dictionaries with comprehension syntax

1
2
3
4
5
6
7
8
9
🐍
Loading PythonSetting up pandas & numpy...

# challenges [2]

# challenge 01/02todo
Write a function called 'double' that takes a number and returns it multiplied by 2. Test it with print(double(5)).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
🐍
Loading PythonSetting up pandas & numpy...
# challenge 02/02todo
Use a list comprehension to create 'squares' containing the squares of [1, 2, 3, 4, 5]. Print the result.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
🐍
Loading PythonSetting up pandas & numpy...

# 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

Filter Permits by Status

# your code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
🐍
Loading PythonSetting up pandas & numpy...