Python Functions

Package reusable behavior.

Python
def average(values):
    return sum(values) / len(values)

print(average([82, 91, 76, 95]))
Output
86.0

Explanation

Define a function with def, give it parameters, and return a result. Calling the function runs its body with the supplied arguments.

Explore the dry run
Guided walkthroughReady
1def average(values):
2 return sum(values) / len(values)
3
4print(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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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