Concepts / Function Definitions and Calls

Function Definitions and Calls

def say_hello(): # block belonging to the function print 'hello world' # End of function say_hello() # call the function say_hello() # call the function again

  • Programming

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.

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.

part of definitiondefinition complete; first call triggers executionfunction can be called multiple timesdef 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 again
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.

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?

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.

Defining and Calling a Simple Function

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

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

Call the function the first time: Write the function name with parentheses. The code inside the function runs.

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

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

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.

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.

execute next linefunction calledenter functionfunction body completeexit function, continue after callprint('Starting')say_hello()Jump to functionprint('hello world')Return to callerprint('Done')
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

  • Forgetting the parentheses when calling a function

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

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

  • Indenting code that should be outside the function

    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.

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

  • Confusing parameters with arguments

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

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

  • Expecting a function to run when you define it

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

    Fix: 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.

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

Key Takeaways

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