Functions#
Functions are used to organize program flow, especially to allow us to easily do commonly needed tasks over and over again. We’ve already used a lot of functions, such as those that work on lists (append()
and pop()
) or strings (like replace()
). Here we see how to write our own functions
A function takes arguments, listed in the ()
and returns a value. Even if you don’t explicitly give a return value, one will be return (e.g., None
).
Here’s a simple example of a function that takes a single argument, i
def my_fun(i):
print(f"in the function, i = {i}")
my_fun(10)
my_fun(5)
in the function, i = 10
in the function, i = 5
functions are one place where scope comes into play. A function has its own namespace. If a variable is not defined in that function, then it will look to the namespace from where it was called to see if that variable exists there.
However, you should avoid this as much as possible (variables that persist across namespaces are called global variables).
functions always return a value—if one is not explicitly given, then they return None, otherwise, they can return values (even multiple values) of any type
a = my_fun(10)
a
in the function, i = 10
Here’s a simple function that takes two numbers and returns their product.
def multiply(a, b):
return a*b
c = multiply(3, 4)
c
12
Quick Exercise
Write a simple function that takes a sentence (as a string) and returns an integer equal to the length of the longest word in the sentence. The len()
function and the .split()
methods will be useful here.
None is a special quantity in python (analogous to null
in some other languages). We can test on None
—the preferred manner is to use is
:
def do_nothing():
pass
a = do_nothing()
if a is None:
print("we didn't do anything")
we didn't do anything
a is None
True
Keyword arguments#
You can have optional arguments which provide defaults. Here’s a simple function that validates an answer, with an optional argument that can provide the correct answer.
def check_answer(val, correct_answer="a"):
return val == correct_answer
print(check_answer("a"))
print(check_answer("a", correct_answer="b"))
True
False
Important
It is important to note that python evaluates the optional arguments once—when the function is defined. This means that if you make the default an empty object, for instance, it will persist across all call.
This leads to one of the most common errors for beginners
Here’s an example of trying to initialize to an empty list:
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
[1]
[1, 2]
[1, 2, 3]
Notice that each call does not create its own separate list. Instead a single empty list was created when the function was first processed, and this list persists in memory as the default value for the optional argument L
.
If we want a unique list created each time (e.g., a separate place in memory), we instead initialize the argument’s value to None
and then check its actual value and create an empty list in the function body itself if the default value was unchanged.
def fnew(a, L=None):
if L is None:
L = []
L.append(a)
return L
print(fnew(1))
print(fnew(2))
print(fnew(3))
[1]
[2]
[3]
L = fnew(1)
print(fnew(2, L=L))
[1, 2]
Notice that the same None
that we saw previously comes into play here.
L
[1, 2]
Lambdas#
Lambdas are “disposible” functions. These are small, nameless functions that are often used as arguments in other functions.
Ex, from the official tutorial: we have a list of tuples. We want to sort the list based on the second item in the tuple. The sort
method can take a key
optional argument that tells us how to interpret the list item for sorting
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda p: p[1])
pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
Here we use a lambda in an extract from a list (with the filter function)
squares = [x**2 for x in range(100)]
sq = list(filter(lambda x : x%2 == 0 and x%3 == 0, squares))
sq
[0,
36,
144,
324,
576,
900,
1296,
1764,
2304,
2916,
3600,
4356,
5184,
6084,
7056,
8100,
9216]
help(filter)
Help on class filter in module builtins:
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.