To group sets of code you can use functions. Functions are small parts of repeatable code.
A function accepts parameters.

Without functions we only have a long list of instructions. Functions can help you organize code. Functions can also be reused, often they are included in modules.

Related course: Complete Python Bootcamp: Go from zero to hero in Python


In the example below we have parameter x and y. Type this program and save it as

#!/usr/bin/env python3

def f(x,y):
return x*y


In this example we have two functions: f(x,y) and print(). The function f(x,y) passed its output to the print function using the return keyword.

function example

Output can also be stored into a variable:

result = f(3,4)


Try the exercises below

1\. Make a function that sums the list mylist = [1,2,3,4,5]

After completing these continue with the next exercise.

Download answers