Concepts / Function Definitions and Calls

Function Definitions and Calls

The critical distinction in programming is between defining a function (writing what it does) and calling a function (actually running it). These are two separate events that happen at different times.

  • 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…

What Is a Function?

A function is a reusable block of code that performs a specific task. Instead of writing the same instructions over and over, you define a function once and then call it whenever you need that task done. Think of a function like a recipe: you write down the steps once, and then whenever you want to make that dish, you follow the recipe rather than reinventing it each time.

Key point

The critical distinction in programming is between defining a function (writing what it does) and calling a function (actually running it). These are two separate events that happen at different times.

Definition Versus Call: When Does Code Run?

When you write a function definition, you are telling the computer what the function should do. The code inside the function does not run at that moment. Instead, the computer simply stores the instructions for later. Only when you call the function does the stored code actually execute.

def say_hello():Definition: code stored,not executedprint('hello world')Still part of definition:stored but not runsay_hello()First call: code insidefunction NOW runssay_hello()Second call: code insidefunction runs againpart of definitiondefinition complete; first call triggers executionfunction can be called multiple times
When does each part of the code execute? The function definition is parsed but not executed. Only when the function is called does the code inside run.
In the real world

Imagine a coffee shop. The barista writes down a recipe for making a cappuccino. Writing down the recipe is like defining a function. The recipe sits on the wall and nothing happens yet. When a customer orders a cappuccino, the barista follows the recipe and actually makes the drink. That is like calling the function. If ten customers order cappuccinos, the barista follows the same recipe ten times. The recipe itself never changes, but it is executed ten times.

Anatomy of a Function Definition

A function definition in Python starts with the def keyword, followed by the function name, parentheses, and a colon. The code that belongs to the function is indented below the definition line.

defKeyword that starts afunction definitionsay_helloName of the function (youchoose this)()Parentheses for parameters(empty if no parameters):Colon marks the start ofthe function blockprint('hello world')Indented code that belongsto the function
What are the parts of a function definition and what does each part do?
Key point

Indentation is crucial. Any code indented under the def line belongs to the function. Once you return to the original indentation level, you are outside the function.

How to Call a Function

To call a function, you write the function name followed by parentheses. This tells the computer to execute the code stored in that function. You can call the same function as many times as you want, and each time the code inside runs again.

Worked example

Defining and Calling a Simple Function

Write a function that prints a greeting, then call it twice.

  1. 1
    Define the function

    Use def followed by the function name, parentheses, and a colon. Indent the code that belongs to the function.

  2. 2
    Call the function the first time

    Write the function name with parentheses. The code inside the function runs.

  3. 3
    Call the function the second time

    Write the function name with parentheses again. The same code runs a second time.

Result

The greeting is printed twice, even though the code was written only once inside the function definition.

python
Output (expected)
hello world
hello world

Notice that we can call the same function twice, which means we do not have to write the same code again. This is one of the main reasons functions exist: to avoid repeating code.

Parameters and Arguments

Definition

A parameter is a name given in the function definition that acts like a variable inside the function. An argument is the actual value you supply when you call the function. Parameters are specified within the parentheses in the function definition, separated by commas. When you call the function, you supply the values in the same way.

Parameters are just like variables except that their values are defined when you call the function and are already assigned values when the function runs. This allows you to write a function once and use it with different data each time you call it.

python
Output (expected)
Hello, Alice
Hello, Bob

In this example, name is the parameter in the function definition. When you call greet('Alice'), the argument 'Alice' is passed to the function, and name takes on the value 'Alice' inside that function call. When you call greet('Bob'), the argument 'Bob' is passed, and name becomes 'Bob'. The same function code runs both times, but with different data.

Key point

Terminology matters: the names in the function definition are called parameters; the values you supply in the function call are called arguments.

Control Flow: Entering and Exiting a Function

When a function is called, the program jumps to the function definition and executes the code inside. Once the function finishes, the program returns to the line right after the function call and continues from there.

print('Starting')say_hello()Jump to functionprint('hello world')Return to callerprint('Done')execute next linefunction calledenter functionfunction body completeexit function, continue after call
How does the program jump into a function when called, and where does it go after the function finishes?
python
Output (expected)
Starting
hello world
Done

The program prints 'Starting', then encounters the function call say_hello(). At that point, it jumps into the function, prints 'hello world', and then returns to the line after the call. Finally, it prints 'Done'. The function definition itself (the def line and its body) is not executed when the program first reads it; it is only executed when the function is called.

Common Mistakes

  • Common mistake

    Forgetting the parentheses when calling a function

    What it looks like
    say_hello instead of say_hello()
    Why it fails

    Without parentheses, you are referring to the function object itself, not calling it. The code inside the function does not run.

    Do this instead

    Always include parentheses after the function name to call it: say_hello()

  • Common mistake

    Indenting code that should be outside the function

    What it looks like

    Indenting a line after the function body when it should be at the original level

    Why it fails

    Indented code is considered part of the function. If you indent too much, code that should run after the function call will instead be part of the function and only run when the function is called.

    Do this instead

    Return to the original indentation level when you want code to be outside the function

  • Common mistake

    Confusing parameters with arguments

    What it looks like

    Thinking the parameter name is the same as the argument value

    Why it fails

    Parameters are placeholders in the definition; arguments are the actual values passed in. They can have different names and values.

    Do this instead

    Remember: parameters are in the definition, arguments are in the call

  • Common mistake

    Expecting a function to run when you define it

    What it looks like

    Writing a function definition and expecting output without calling it

    Why it fails

    Defining a function only stores the code. It does not execute until you call it.

    Do this instead

    Always call the function separately after defining it

Why Functions Matter

Functions are one of the most important tools in programming. They allow you to write code once and reuse it many times. This saves time, reduces errors, and makes your code easier to understand and maintain. Instead of copying and pasting the same code over and over, you define a function and call it whenever you need that functionality.

Key point

A well-designed function does one thing well and can be called from many places in your program. This principle of reusability is central to writing clean, efficient code.

Practice

EASY

Write a function called introduce that takes a parameter name and prints 'My name is ' followed by the name. Then call the function twice with two different names.

Hints
  • Start with def introduce(name):
  • Use print() with string concatenation or an f-string
  • Call the function twice with different arguments
MEDIUM

Define a function called add_numbers that takes two parameters, adds them together, and prints the result. Call it three times with different pairs of numbers.

Hints
  • Use two parameters separated by a comma
  • Use the + operator to add the parameters
  • Call the function three separate times

Summary

  1. 1
    A function definition tells the computer what code to run, but the code does not execute until the function is called.
  2. 2
    A function call is when you write the function name with parentheses, which triggers the code inside the function to run.
  3. 3
    You can call the same function multiple times, and the code inside runs each time.
  4. 4
    Parameters are variable names in the function definition; arguments are the actual values you pass when calling the function.
  5. 5
    Indentation determines which code belongs inside a function and which code is outside.
  6. 6
    When a function is called, the program jumps to the function, executes its code, and then returns to the line after the call.

At a glance

  • A function definition stores code for later use; a function call actually runs that code.
  • Define a function with def, a name, parentheses, a colon, and indented code; call it by writing the name with parentheses.
  • Parameters in the definition are placeholders; arguments in the call are the actual values passed to the function.
  • Functions allow you to write code once and reuse it many times, avoiding repetition and making programs cleaner.
  • Control flow enters a function when it is called and returns to the next line after the call when the function finishes.

Related concepts

More concepts starting with F