Defining and Calling Functions

A function definition gives a computation a name.

This defines the function. It does not run the function yet.

To run it, call it:

greet()

Output:

hello

Definition Versus Call

These are different actions:

This creates the function.

greet()

This runs it.

The parentheses matter. Without them, you are referring to the function object, not calling it.

The Function Body

The indented lines belong to the function:

Both print() calls run when show_pair() is called.

Define, then call

The body runs only when the function is called.

Runs locally with Python in your browser.

Ready to run.

Order Matters

Python needs to see the definition before the call:

This fails because show_pair is called before Python knows that name.

Defining Is Not Calling

Forgetting to call the function:

This program prints nothing. Add:

greet()
Exercise: Definition or call

Which line runs the function?

  1. def greet():
  2. greet()

Compute it first, then check your number.

HintLook for call parentheses

A definition begins with def. A call uses the existing function name followed by parentheses.

SolutionLine two calls the function

def greet(): creates the function. greet() calls it, so the answer is line 2.

Functions Run Only When Called

Defining a function prepares it. Calling a function runs it.