Functions#
Python functions work in much the same way as C++ functions.
Here’s a simple function that takes a single argument:
def func(i):
return 2 * i
Notice:
We start functions in python with the
defkeyword, followed by the function name, argument list, and a:.Since python is dynamically typed, we don’t need to specify the argument type (
i) or the type of the return value.The body of the function is indented.
We can call this function simply as:
a = func(2)
Note
python functions always return a value. If you do not include a
return statement, then a special quantity, None will be
returned.
Keyword arguments#
We can have keyword arguments to a function. If we do not provide a value for these arguments when we call the function, then the default value is used.
Here’s an example:
def my_sin(theta, in_degrees=False):
if in_degrees:
return math.sin(math.radians(theta))
return math.sin(theta)
If we call this without specifying in_degrees, then the function will treat theta as in radians.
If we set in_degrees=True when we call the function, then it will treat it as degrees.
For example:
my_sin(math.pi/4)
my_sin(45, in_degrees=True)
Lambda functions#
Just like C++, python has lambda functions. They are used in much the same way—sometimes we need a function once, as an argument to another function.
The syntax of a lambda function is: lambda args : statement,
where args are the arguments of the function.
Note
Python lambda functions are limited to a single statement in the function body.
Furthermore, we do not use an explicit return statement.
As an example, consider the sort function on a list—it can take a key argument that provides a function used for sorting (much like we saw in C++).
We can rewrite our C++ sorting example (see Sort Example) in python:
titles = ["a new hope",
"the empire strikes back",
"return of the jedi",
"the phantom menace",
"attack of the clones",
"revenge of the sith",
"the force awakens",
"the last jedi",
"the rise of skywalker"]
# sort by string length
titles.sort(key=lambda s: len(s))
for s in titles:
print(s)
Some examples#
Trapezoid rule integration#
Let’s rewrite our Trapezoid rule example in python. We
want a python function trapezoid that takes a range and a function
to integrate.
import math
def trapezoid(a, b, N, func):
"""Integrate function func(x) from a to b using N intervals of
the trapezoid rule."""
dx = (b - a) / N
I = 0
for n in range(N):
xl = a + dx * n
xr = a + dx * (n+1)
fl = func(xl)
fr = func(xr)
I += 0.5 * dx * (fl + fr)
return I
# test out our trapezoid rule
a = 0.5
b = 1.5
I_exact = 1.0 - 1.0 / (2.0 * math.pi**2)
for N in [2, 4, 8, 16, 32, 64, 128]:
I = trapezoid(a, b, N,
lambda x: 1.0 + 0.25 * x * math.sin(math.pi * x))
err = abs(I - I_exact)
print(f"{N:3} {I:7.5f} {err:9.6g}")
Notice:
In python, the function that we pass into
trapezoid()is treated like any other object, and we don’t need to give it a special type or other specifier.We have a multi-line string just after the function definition (in python, multi-line strings use triple quotes, “””. This is a docstring—this is what
help()provides when we ask about a function.If we do:
help(trapezoid)
you’ll see this help.
We use a lambda-function to pass in the integrand.