본문으로 건너뛰기

P3 — Writing Small Python Functions

About 110 min

Begin this optional module before L2.3 — Activation Functions. L2.3 is the first regular Lab where you complete a function yourself. P1 and P2 taught reading code, values, and arrays; P3 teaches writing a few lines. The following multiple-choice questions are a reading check, not proof that you can write working functions. Neither this check nor the Lab changes course progress.

Quick Check

1. What is returned by def f(x): return x + 1 when f(4) is called?
2. What should a ReLU function return for [-2, 0, 3]?
3. Which block visits every case before returning one dictionary?
4. What does if not values detect when values is a list?
5. Where is the most helpful place to start reading a Python Traceback?

0 of 5 questions answered.

If you can pass the Browser Lab below without opening a hint in about 10 minutes, you can skip to L2.3. That is a fluency check: most first-time learners should plan on the 35–40 minutes budgeted below.

Goal

Write small functions using def, return, if, for, and comprehensions. Check their behavior with assert and use errors or Tracebacks to locate the first incorrect step before returning to TODO Labs.

Function input and output​

def defines a reusable operation with parameters. Its body is indented. return sends a value back to the caller; print only displays a value and cannot replace a return result used by a test.

def double(number):
return number * 2

answer = double(3)
print(answer) # 6
assert answer == 6

The name number exists inside the function. The assignment answer = double(3) stores the returned value. If the function has no explicit return, it returns None. To complete a Lab TODO, keep the function name and parameters as provided: hidden checks will call them.

if and elementwise conditions: this pattern returns in L2.3​

An if tests one condition. Use else for the alternative. The colon starts an indented block; matching indentation tells Python which lines belong to it.

def distance_from_zero(value):
if value < 0:
return -value
return value

assert distance_from_zero(-5) == 5
assert distance_from_zero(4) == 4

To apply a one-value rule to every element of a list, use a comprehension. This elementwise-condition pattern returns in L2.3, where the rule and the input type (a NumPy array) are different; work that rule out in the L2.3 Lab itself.

def distances_from_zero(values):
return [distance_from_zero(value) for value in values]

assert distances_from_zero([-5, 0, 3]) == [5, 0, 3]

Check negative, zero, and positive cases, not just the happy path. A function that works only for positive input has not handled every case.

Predict

If a function returns inside a for loop after checking its first case, how many cases are processed?

for loops and branches: this pattern returns in L8.11​

A for loop handles each item in a collection. Build a dictionary by assigning to a key after making a decision. This example chooses packing materials for store items, not model-comparison outcomes:

def packing_labels(items):
labels = {}
for item in items:
if item["fragile"]:
label = "padded"
elif item["weight_kg"] > 10:
label = "heavy"
else:
label = "standard"
labels[item["sku"]] = label
return labels

assert packing_labels([
{"sku": "mug", "fragile": True, "weight_kg": 1},
{"sku": "book", "fragile": False, "weight_kg": 1},
]) == {"mug": "padded", "book": "standard"}

elif means “otherwise, if ...”; else handles all remaining items. The dictionary key stores the label for each SKU. Returning after the loop ensures that all input items are processed. This loop-and-branch pattern returns in L8.11, where the data and output contract are different. You will work out that later Lab's rules there.

List slices and paired iteration​

A list slice uses items[start:stop]. The start is included and the stop is excluded; leave either side blank to use the beginning or end. A negative stop counts back from the end.

colors = ["red", "green", "blue", "gold"]
assert colors[:2] == ["red", "green"] # From the beginning
assert colors[1:3] == ["green", "blue"] # A middle range
assert colors[:-2] == ["red", "green"] # Stop two entries before the end
assert ["?"] * 3 == ["?", "?", "?"] # Repeat a list for padding

When you need both each item and its position, enumerate supplies pairs. When you need items from two lists side by side, zip supplies pairs. Use the given names rather than assuming that the current item is already an index:

for position, color in enumerate(colors, start=1):
print(position, color)

counts = [2, 3]
unit_prices = [5, 7]
for count, price in zip(counts, unit_prices):
print(count * price)

zip stops at the shorter input. These examples show syntax, not the padding, shifted-token, or positional-encoding rules you must work out in the later Labs.

List and dictionary comprehensions​

A comprehension is a compact way of building a collection. Write it only after you can explain its loop in words:

values = [-2, 0, 3]
squares = [value * value for value in values]
lengths = {"train": 6, "test": 2}
doubled = {name: count * 2 for name, count in lengths.items()}

The part before for is the value you produce. In a dictionary comprehension, name: count * 2 means the new key and value. .items() yields each dictionary's key and value pair. [x for x in values if x > 0] includes an optional filter: it does not change the original values list.

Tiny Python operations you will use in the Lab​

These operations are small building blocks. Practice reading them before combining them into a function:

name = " Ada "
assert name.strip() == "Ada" # Remove surrounding whitespace
assert name.strip().lower() == "ada" # Also convert letters to lowercase

ages = [18, 21, 15]
assert sum(ages) == 54 # Add every number in a list
assert len(ages) == 3 # Count the list entries

inventory = {"pens": 2, "pads": 3}
assert sum(inventory.values()) == 5 # Read and add dictionary values

visits = {"north": 1}
if "south" not in visits: # True when the key is absent
visits["south"] = 0
visits["north"] += 1 # Same as visits["north"] = visits["north"] + 1
assert visits == {"north": 2, "south": 0}

A blank string like " " becomes "" after .strip(). if not values detects an empty list or dictionary; sum([]) is 0, but len([]) is 0 too, so check for an empty list before dividing by its length. Use these pieces to build your own solution—the code above does not implement any Lab TODO.

Transforming a dictionary: this pattern returns in L9.6​

A function can create a new dictionary from the keys and values of another. Here a shop adds a sales tax rate to item prices:

def prices_with_tax(prices, tax_rate):
return {
item: round(price * (1 + tax_rate), 2)
for item, price in prices.items()
}

assert prices_with_tax({"pen": 2.0, "pad": 5.0}, 0.1) == {
"pen": 2.2, "pad": 5.5
}
assert prices_with_tax({}, 0.1) == {}

The new dictionary keeps the same keys and changes only the values. .items() provides each key–value pair; an empty dictionary produces an empty result. This dictionary-transformation pattern returns in L9.6, but that Lab asks you to derive a different formula and handle its own edge cases. We do not solve it here.

Read an assert and a Traceback​

An assert checks a condition. If it is false, Python raises AssertionError. This is useful for small, local checks while you develop an exercise, but is not a substitute for validation in a deployed system.

assert distances_from_zero([-1, 0, 2]) == [1, 0, 2]
assert packing_labels([{"sku": "box", "fragile": False, "weight_kg": 12}]) == {"box": "heavy"}
assert prices_with_tax({"pencil": 1.0}, 0.1) == {"pencil": 1.1}

A Traceback reports which call and file line led to an exception. Read from the final line upward: NameError suggests an unknown or misspelled name; TypeError often means the operation got an incompatible type; IndexError means a list position does not exist; KeyError means a dictionary key does not exist; ZeroDivisionError means a denominator is zero. In a syntax or indentation error, examine the marked line and the line just above it.

For example, if you accidentally write item["mass"] where the data uses "weight_kg", the exception might finish with KeyError: 'mass'. Check the dictionary keys instead of changing the packing rules.

A small debugging sequence​

  1. Reproduce the failure with the smallest input that triggers it.
  2. Read the exception type or failing assertion and its exact line.
  3. Print one intermediate value, its type or shape, and compare it with the input contract.
  4. Fix one cause, then run the original test and a contrasting edge case.
  5. Reset deliberate experiments that are not part of the final answer.

This prevents blind rewrites of working code. For each TODO, check ordinary input and an edge case, and make sure the returned structure matches the grader's expected type.

Browser Lab: six independent function challenges​

The starter has six short TODOs. They use the syntax from the examples above, but solve different problems. Do not copy the examples as answers.

  1. Function and return — celsius_to_fahrenheit(celsius): convert a Celsius temperature to Fahrenheit using celsius * 9 / 5 + 32.
  2. if — clip(value, low, high): return a value inside the inclusive range [low, high]; assume low <= high.
  3. for, if, and dictionary accumulation — count_order_statuses(orders): count each order["status"]. An empty list gives {}.
  4. List comprehension — clean_tags(tags): strip whitespace, remove blank tags, and lowercase the remaining strings while keeping their order.
  5. Dictionary comprehension — percentage_scores(scores): convert nonnegative scores to percentages of the total, keeping each key. When the total is zero, return 0.0 for every key; an empty dictionary stays empty.
  6. Empty-input edge case — average_or_zero(values): compute the mean, or return 0.0 when there are no values.

For each TODO, test one ordinary input and one edge case. In the Lab, choose a TODO number to reveal three hints for that problem only: an approach, a syntax clue, and finally just that function's answer. Other functions stay hidden until you choose them. Opening a hint is fine for learning, but the skip criterion above applies only if you can solve the Lab without hints.

Loading lab…

Budget about 35–40 minutes for six TODOs and another 10 minutes to vary inputs and inspect failed assertions. Change one input deliberately, read the resulting failure, then restore the working version.

Quick Check

1. What is the difference between print(result) and return result?
2. Where should return results be placed if all cases must be classified?
3. What should you do before dividing when the total could be zero?

0 of 3 questions answered.

Key Takeaways

  • def declares parameters and an indented body; return gives the caller a result.
  • if/elif/else chooses among cases; for processes all cases.
  • List and dictionary comprehensions construct new collections from repeated input items.
  • assert makes expected behavior executable; test boundaries, empty inputs, and zero totals.
  • Read Tracebacks from the final error message toward the relevant code line, then fix one cause at a time.

Continue to L2.3 — Activation Functions. Its Lab applies an elementwise rule to a NumPy array; use the if and elementwise reasoning from this guide to work it out.