Functions
In Python, functions are reusable blocks of code that accept input arguments and return one or more values. As we have seen, a method is a special type of function that is contained within an object. We typically do not refer to methods as “functions,” instead reserving the term for functions that are not methods. A function that computes the square root of the sum of the squares of two arguments can be defined as:
def root_sum_squared(arg1, arg2):
= arg1**2 + arg2**2
sum_squared return sum_squared**(1/2)
The syntax requires the block of code following the def
line to be
indented. A block ends where the indent ends. The indent should, by
convention, be 4 space characters. The function ends with a return statement, which begins with the keyword
return
followed by an expression, the value of which is returned to the caller
code. The variable sum_squared
is
created inside the function, so it is local to the function and cannot
be accessed from outside. Calling (using)
this function could look like
3, 4) root_sum_squared(
This call returns the value 5.0
.
The arguments arg1
and arg2
in the previous example are called
positional arguments because they are
identified in the function call by their position; that is, 3
is identified
as arg1
and 4
is identified
as arg2
based on their positions
in the argument list. There is another type of argument, called a keyword argument (sometimes called a “named”
argument), that can follow positional arguments and have the syntax
<key>=<value>
.
For instance, we could augment the previous function as follows:
def root_sum_squared(arg1, arg2, pre="RSS ="):
= arg1**2 + arg2**2
sum_squared = sum_squared**(1/2)
rss print(pre, rss)
return rss
The pre
positional argument
is given a default value of "RSS ="
,
and the function now prints the root sum square with pre
prepended. Calling this function
with
4, 6) sum_squared(
prints the following to the console:
RSS = 7.211102550927978
Alternatively, we could pass a value to pre
with the call
4, 6, pre="Root sum square =") sum_squared(
which prints
Root sum square = 7.211102550927978
Online Resources for Section 1.9
No online resources.