Writing Your Own Functions · practice
Define and Call a Function
Your first
def show_welcome():
print("Welcome to the trail.")
Read the first line from left to right:
deftells Python you are defining a function.show_welcomeis the function’s name.()is where parameters will go later. Empty parentheses mean this function expects no information.:starts the indented body.
The body belongs to the function:
print("Welcome to the trail.")
The same four-space indentation you used for
Calling the function
After Python has reached the definition, you can call the function by writing its name followed by parentheses:
The body runs once for each call. The definition itself still runs no body lines.
Python must know the name first
Programs run from top to bottom. This order works:
def show_welcome():
print("Welcome to the trail.")
show_welcome()
This order does not:
show_welcome()
def show_welcome():
print("Welcome to the trail.")
At the first line, Python has not reached the definition yet, so the name show_welcome does not exist. The result is a
You will usually place function definitions near the top of a short program and the calls that start the work below them.
A call temporarily changes where Python works
When Python reaches show_welcome(), it moves into the function body. After the body ends, Python returns to the line after the call.
The output keeps the program’s actual order:
Before the call
Ding!
After the call
This jump into a function and back to its caller is the basic rhythm behind every function you will write.
The placeholder in the next starter
Python requires an indented body after every def line. In the next exercise, the unfinished body contains this temporary placeholder:
def describe_trip(name, place):
pass
pass means “do nothing here.” It lets incomplete starter code remain valid Python. Replace it with the real body the exercise asks for; a function that reaches only pass does no useful work and returns no useful result.
Which first line correctly defines a function named show_map that expects no information?
Task
Define and call a show_status.
Your program must:
define
show_statuswith no; print exactly
Ready to learn.inside the function;call
show_status()exactly once after its definition.
Expected output:
Ready to learn.
After it works, use Step in the exercise editor. Notice when Python remembers the definition, when the call enters the body, and where execution continues after the body ends.