Every exercise in 60_meet_marimo.py, with the solution and why it works. Each answer stays closed until you swear you tried it first. Opening one changes nothing in your notebook; your check still has to go green from your own code. Read the whole notebook, with its lessons.
Exercise 7.1. Running totals
The task
A running total is the kind of thing that tempts a notebook into hidden state: in Jupyter, a cell with total = total + x, run again and again. In marimo that cell is refused, and the right shape is a function that gives back every total at once.
Finish running_totals(values) so that it returns a list with the total so far after each value.
| call | returns |
|---|---|
running_totals([5, 7, 2]) |
[5, 12, 14] |
running_totals([]) |
[] |
If the check is red: common causes
- Only the grand total: the function returns the total, not the list of totals.
- The values themselves (
[5, 7, 2]): the value is appended instead of the total so far. - One total too few or too many: append once per value, after adding it.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Keep the total inside the function, where it starts at zero on every call, and record it after each value: the list is every intermediate total, made in one pass.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def running_totals(values): total = 0 totals = [] for value in values: total = total + value totals.append(total) return totalsWhy each part is there
total = 0inside the function means every call starts afresh; a total kept in a notebook cell would carry over from one run to the next.totals.append(total)after adding each value records the total so far, so the list has one entry per value, and the last entry is the grand total.- The list is the function's own, so appending to it is fine, and an empty input gives an empty list.