Concepts / Defining a Function

Defining a Function

The parentheses are part of the function-definition structure even when no parameters are shown. The indented block is also part of the structure: it contains the statements that Python will run when the function is called.

  • Programming
Interactive lab

Try it: Defining and Calling Functions

What def and a call really do: def only creates a function object, a call binds the arguments to the parameters in a new frame and runs the body, return ends the call at once and its value replaces the call expression in the caller — while a function that only prints gives back None.

How it works

  1. def name(params): creates a function object and binds the name to it; the body does not run yet.
  2. A call evaluates its arguments, opens a new frame, binds each parameter to its argument and runs the body from the top.
  3. return value ends the call immediately (lines after it never run) and sends the value back; the frame and its local names are discarded.
  4. In the caller, the call expression is replaced by the returned value, which can be stored, used in a larger expression or passed to another call.
  5. A body that ends without return (e.g. one that only prints) makes the call evaluate to None — so x = f() stores None and None + 1 raises TypeError.
  6. Calling a name before its def has run raises NameError: the function does not exist yet.

Default run (18 steps): The program is ready. Python runs it from the top, one statement at a time. Idea: the value a call returns is what the caller stores. … The program finished. Console: 8.

Simplified: Four fixed, hand-written programs; you edit the literal arguments, switch the body between return and print, and move the def after the calls. The lab's own small evaluator runs them (your input is never executed as code); every variant was run in CPython 3.12 and the lab reproduces its sys.settrace line/call/return/exception events, its output and its error message. Functions are shown as <function name> without a memory address.

Educational simulation

Loading the simulation…

Instructions for Later

A function definition creates a reusable block of code, but creating that block does not immediately run the instructions inside it. When Python encounters a definition, it stores the instructions under the function's name. The instructions run later, when the function is called. Keeping these two actions separate is essential for understanding why a program may define a function without producing output immediately.

What do you think happens?

What happens when Python reads this definition before any call appears?

  • The function body runs immediately

  • The function is stored for later use

  • Python returns to the definition repeatedly

  • The function is deleted

Reveal answer
Answer:

The function is stored for later use

Defining a function stores it in memory but does not execute the code inside. A function call is what executes the body.

Definition Line Anatomy

A Python function definition begins with the def keyword. The function name follows it, then a pair of parentheses, and then a colon. The colon marks the end of the definition line and signals that an indented block of statements follows. Together, these parts tell Python that the following indented statements belong to a named function.

python
defstarts a definitiongreetfunction name()parameter area:ends the definition lineindented bodystatements to run later
What does each part of a function definition contribute to the structure?
Key point

The parentheses are part of the function-definition structure even when no parameters are shown. The indented block is also part of the structure: it contains the statements that Python will run when the function is called.

Definition and Call

ActionWhat Python doesWhen the body runs
Function definitionStores the function and its instructions in memoryNot during the definition
Function callJumps to the function definition and runs its bodyDuring the call

A definition prepares instructions; a call requests their execution.

A definition and a call have different jobs. In a definition, the name is introduced and the indented instructions are stored for later use. In a call, the function's name is used to request execution. Python then runs the stored body and returns to the line after the call.

def greet():stores instructionsgreet()runs instructionsprint("Hello")function bodylaterexecutes
How does preparing a function differ from requesting its execution?
Code walkthrough
def greet():
    print("Hello")

greet()
  1. 1
    Python reads the definition and stores the function instructions.
  2. 2
    Python reaches the call greet().
  3. 3
    Python runs the indented print statement.
  4. 4
    The program continues after the call.
  • The definition stores the function named greet.
  • The indented print statement belongs to the function body.
  • The call greet() causes the body to execute.
Output
Hello

Execution Path

The control flow has a clear order. First, Python encounters the definition and stores the function. It then continues to the next statement instead of entering the body. When Python later reaches a call, it jumps to the stored definition, runs the body, and then returns to the line after the call. The definition is therefore encountered before the call, while the body is executed only during the call.

Read definitionstore functionNext statementcontinue normallygreet()request executionFunction bodyrun statementsAfter the callresume controldefinition completelaterjump toreturn to
In what order does control move from a definition through a later call and back?
Worked example

Tracing a Greeting

Determine when the message is displayed in this sequence: a function definition followed by a function call.

  1. 1
    Read the definition

    Python stores the function named greet and its indented print instruction. The print instruction does not run yet.

  2. 2
    Reach the call

    Python reaches greet(), which requests execution of the stored function.

  3. 3
    Run the body

    Python runs the print instruction inside the function body.

  4. 4
    Continue

    After the body finishes, control returns to the line after the call.

Result

The message is displayed when greet() is called, not when greet is defined.

Indentation Boundaries

The colon at the end of the definition line signals that an indented block follows. Statements in that indented block belong to the function body. The body is the set of instructions Python will run when the function is called. Indentation therefore shows which statements are inside the function rather than outside it.

python
greetfunctionprint("Hello")indented body statementprint("Outside thefunction")outside statementcontains
Which statement belongs to the function body, and which statement is outside it?

Mistakes in Definitions

  • Common mistake

    Forgetting the colon after the parentheses

    What it looks like
    def greet()
        print("Hello")
    Why it fails

    The colon marks the end of the definition line and signals that an indented block follows.

    Do this instead
    def greet():
        print("Hello")
  • Common mistake

    Not indenting the function body

    What it looks like
    def greet():
    print("Hello")
    Why it fails

    The statements that belong to the function must form an indented block after the colon.

    Do this instead
    def greet():
        print("Hello")
  • Common mistake

    Defining a function without calling it

    What it looks like
    def greet():
        print("Hello")
    Why it fails

    The definition stores the instructions but does not execute the body.

    Do this instead
    def greet():
        print("Hello")
    
    greet()
  • Common mistake

    Calling a function before defining it

    What it looks like
    greet()
    
    def greet():
        print("Hello")
    Why it fails

    A function call must refer to the function after it has been defined and stored.

    Do this instead
    def greet():
        print("Hello")
    
    greet()
Incomplete definitionmissing colon orindentationComplete definitioncolon and indented bodycorrect syntax
How do missing syntax elements and indentation change a function definition into a correctly structured one?
Best practice

When checking a function definition, inspect the structure from left to right: confirm def, confirm the function name, confirm the parentheses, confirm the colon, and then confirm that the body is indented. Finally, check whether the function is called after its definition.

Practice the Trace

EASY

Write a function definition named welcome with an indented statement that displays a message, then add a call so that the body executes. As you write it, label the definition, the body, and the call in your own notes.

Hints
  • Start the definition with def.
  • Place parentheses and a colon after the function name.
  • Indent the statement that belongs to the body.
  • Place the call after the definition.
EASY

A function is defined correctly, but nothing from its body appears to happen. What should you check first, and why?

Hints
  • Look for a function call.
  • Remember that defining stores the instructions, while calling executes them.

Key Takeaways

  1. 1
    A function definition uses def, a function name, parentheses, a colon, and an indented block.
  2. 2
    Defining a function stores its instructions but does not execute the body.
  3. 3
    Calling a function runs the body and then returns control to the line after the call.
  4. 4
    The colon signals the indented function body, and indentation determines which statements belong to it.
  5. 5
    Common mistakes include forgetting the colon, failing to indent the body, defining without calling, and calling before defining.

At a glance

  • A function definition creates a named, reusable block of instructions.
  • The def keyword, function name, parentheses, colon, and indented body form the basic definition structure.
  • Python stores a function when it reads the definition and executes its body only when the function is called.
  • After the body finishes, control returns to the statement after the call.
  • Checking syntax, indentation, definition order, and the presence of a call helps correct common mistakes.

More concepts starting with D