Python Functions
Package reusable behavior.
On this page
The concept
Define a function with def, give it parameters, and return a result. Calling the function runs its body with the supplied arguments.
Code example
Python
def average(values):
return sum(values) / len(values)
print(average([82, 91, 76, 95]))Output
86.0
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
Guided walkthroughReady
1
def average(values):2
return sum(values) / len(values)3
4
print(average([82, 91, 76, 95]))Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Define average; its body waits until the function is called. | — | — | |
| Create the list and call average with it. | values = [82, 91, 76, 95] | — | |
| sum is 344 and len is 4; return 344 / 4. | return = 86.0 | — | |
| Print the returned value. | return = 86.0 | 86.0 |
Behind the scenes
How Python processes this code
Python runs this source through its interpreter. It creates objects for values and resolves names as each statement runs.