Functions and Lists: Mechanism

30 min
0/5 practice checks

Mechanism

Follow the mechanism step by step and distinguish what causes the change from what is merely observed.

This extension applies that lens specifically to Functions and Lists.

Functions: naming a block of steps

When you find yourself writing the same steps again and again, wrap them in a function. A function has a name, can take inputs (parameters) inside the brackets, and can return a result.

def area(length, width):
    return length * width

print(area(5, 3))   # 15
print(area(10, 2))  # 20

def starts the definition. You call the function by writing its name with values in the brackets. return hands a value back to whoever called it.

python

Runs in your browser. Charts (matplotlib) are not supported — use print-based output.

Lists: many values in one box

A single variable holds one value. A list holds many, in order, inside square brackets:

temps = [21, 24, 19, 28, 23]
print(temps[0])     # 21  (first item, index 0)
print(len(temps))   # 5   (how many items)
temps.append(30)    # add 30 on the end

Each item has an index (position) starting at 0. Useful tools: len(list) counts items, list.append(x) adds one, sum(list) totals numbers.

Looping over a list

A for loop can walk through every item in a list, which is where functions and lists become powerful together:

temps = [21, 24, 19, 28, 23]
hot_days = 0
for t in temps:
    if t >= 25:
        hot_days = hot_days + 1
print(hot_days)   # 1

The loop variable t becomes each temperature in turn, and the if counts the hot ones.

python

Runs in your browser. Charts (matplotlib) are not supported — use print-based output.

Coding: Text Programming Foundations — Mechanism: Given this list:

rivers = ["Orange", "Vaal", "Limpopo", "Tugela"]
print(rivers[1])

What is printed?

Coding: Text Programming Foundations — Mechanism: A function returns the average of a list:

def average(values):
    return sum(values) / len(values)

marks = [60, 80, 70, 90]
print(average(marks))

What number is printed?

Coding: Text Programming Foundations — Mechanism: Which Python list method adds a new item to the end of a list, as in chores.____("sweep")? (One word, no brackets.)

Name the original topic being extended by this mechanism lesson.

Which statement is the best evidence-led starting point for Functions and Lists: Mechanism?