Before you run it, say out loud what it will print. Then open the answer.
What it prints
no output yet
2
Run them in order.
show(work(read_data()))
Before you run it, say out loud what it will print. Then open the answer.
What it prints
6
3
Put the plan in a main function and call it.
def main():
items = read_data()
total = work(items)
show(total)
main()
Before you run it, say out loud what it will print. Then open the answer.
What it prints
6
4
Call one piece alone with your own values.
print(work([2, 2]))
Before you run it, say out loud what it will print. Then open the answer.
What it prints
4
Put it in order
Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.
Data Flow
Each idea becomes its own function, and the program is the list of those names in order.
1read_data returns items
↓
2work returns a total
↓
3show prints it
↓
4main names the steps
Line by line
Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.
def read_data():sets nothing on screen
return [1, 2, 3]sets nothing on screen
def work(items):sets nothing on screen
return sum(items)sets nothing on screen
def show(total):sets nothing on screen
print(total)no output yet
Why this worksTop down
Start by naming the steps of the whole job. Each name becomes a function, and each function is split the same way until the steps are one or two lines.
Why small functions help
A small function has a name, an input, and an output. That shape can be read, tested, moved, and deleted on its own. A long block cannot.