Python for Programmers: Functions
Welcome to the Functions lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
We can define functions with the
defkeyword. Note the:after the argument list!>
def double(x):return 2 * xdouble(2)Result:
4
When a function has no explicit return value, it returns
None, which is Python's null value. Another lesson will coverNonein more detail. To avoid this, remember to use thereturnkeyword!>
def double(x):2 * xdouble(2)Result:
>
def add(a, b):# We forgot the `return` keyword!a + badd(2, 3)Result:
None
Python functions are "first-class values", which means that we can use them in the same way that we use any other value, like
4or[1, 2, 3].All Python values have attributes that we can inspect. Even functions have attributes, like
.__name__for example. By default, this is the same name we gave the function, so the functiondoublehas the name'double'.>
def double(x):return 2 * xdouble.__name__Result:
'double'
Because functions are first-class values, they can be passed as arguments. In the next few examples, we write an
apply_twicefunction that takes any functionf, then doesf(f(x)).>
def apply_twice(f, value):return f(f(value))- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
def add1(x):return x + 1apply_twice(add1, 3)Result:
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
def double(x):return x * 2apply_twice(double, 3)Result:
12
- Note: this code example reuses elements (variables, etc.) defined in earlier examples.
>
def append_s(some_string):return some_string + "s"apply_twice(append_s, "happine")Result:
'happiness'
In future lessons, we'll see first-class functions used idiomatically in Python code.
Finally, a note on terminology. Strictly speaking, functions accept "parameters", but we pass "arguments" when calling them. However, in Python, the word "argument" is normally used for both ideas: functions accept arguments, and we pass arguments to functions. We'll follow that convention in this course, using the term "argument" for both ideas.