Why wrap steps in a name
A name gives a reader a word for a job. Instead of reading the same three lines every time they appear, you read the name and know the job. That is the first reason functions exist.
A function is a named block of steps you can run again and again. You write it once and call it by name as many times as you like.
About 2 min of reading
Make and call your first function.
Define a function that prints a line.
Before you run it, say out loud what it will print. Then open the answer.
Call it once.
Before you run it, say out loud what it will print. Then open the answer.
Call it again to see reuse.
Before you run it, say out loud what it will print. Then open the answer.
Put the call above the def and watch it fail.
Before you run it, say out loud what it will print. Then open the answer.
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.
Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.
A name gives a reader a word for a job. Instead of reading the same three lines every time they appear, you read the name and know the job. That is the first reason functions exist.
A definition describes a job and runs nothing. A call runs the job. Keeping these two apart is the mental model every later lesson builds on.
def greet():
print("hello")
greet()
The def line makes the function but runs nothing. The call greet() on its own line is what runs the steps inside.
def show_total():
print(2 + 3)
show_total()
show_total()
The name show_total stands for the job. Calling it twice runs the same two steps twice, which is the whole point of a function.
def placeholder():
pass
placeholder()
A function body cannot be blank, so pass is the placeholder that means do nothing. It keeps the shape valid while you fill in the steps later.
run_it()
def run_it():
print("ok")
Calling a function before it is made fails. The def has to run first so the name exists, which is why definitions go above the calls.