Tip: Choose Save as PDF in the print dialog to download. Use A4 paper size.
This Side effects and pure functions worksheet is part of the WA Computer Science ATAR Year 11 — Modular Programming journey. Print it as a booklet?
Shade in the A or B circle for each question.
Draw a line connecting each item on the left to its match on the right.
| Left column | Right column | |
|---|---|---|
| 1def add_item(items): items.append(5) | Aassert square(4) == 16 | |
| 2def double(n): return n * 2 | Bsort() changes the passed-in list, which is a side effect, so it is not pure. Use return sorted(nums) to leave the original alone. | |
| 3A function that changes a global variable has a side effect | CThe function prints, which is a side effect, and returns nothing, so x = None + 1 causes a TypeError. It should return sum(nums). | |
| 4A pure function is easier to test because the output depends only on its inputs | Ddef add_point(): global score score += 1 | |
| 5def total(nums): print(sum(nums)) x = total([1, 2]) + 1 | EA side effect: the function changes the list that was passed in, so the caller's list is altered | |
| 6def sorted_copy(nums): nums.sort() return nums | FA pure function: it only uses its input and returns a result, changing nothing outside itself |
Complete each line of code by filling in the missing parts.
Shade in the letter of the line that contains an error.
side effect — A change a function makes outside itself, like printing, editing a global or changing a passed-in list. A pure function has no side effects and only returns a result from its inputs.def show(n):
print(n * 2)def add(n):
global total
total += ndef push(items, x):
items.append(x)def plus(items, x):
return items + [x]def double(n):
return n * 2
assert double(4) == 8