0%

Writing Your Own Functions · practice

Define and Call a Function

Your first will do one fixed job. No and no result for the caller to use yet. That keeps your attention on the shape of a definition.

def show_welcome():
    print("Welcome to the trail.")

Read the first line from left to right:

  • def tells Python you are defining a function.

  • show_welcome is 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 statements and marks the lines that are part of the function.

Calling the function

After Python has reached the definition, you can call the function by writing its name followed by parentheses:

Try it

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.

Try it

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 named show_status.

Your program must:

  1. define show_status with no ;

  2. print exactly Ready to learn. inside the function;

  3. 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.