Functions
Most
statements in a typical Python program are organized into functions.
A function is a group of statements that
executes upon request. Python provides many built-in functions and
allows programmers to define their own functions. A request to
execute a function is known as a function
call. When a function is called, it may be
passed arguments that specify data upon which the function performs
its computation. In Python, a function always returns a result value,
either None or a value that represents the results
of its computation. Functions defined within class
statements are also called methods. Issues
specific to methods are covered in Chapter 5; the
general coverage of functions in this section, however, also applies
to methods.
In Python, functions are objects (values) and are handled like other
objects. Thus, you can pass a function as an argument in a call to
another function. Similarly, a function can return another function
as the result of a call. A function, just like any other object, can
be bound to a variable, an item in a container, or an attribute of an
object. Functions can also be keys into a dictionary. For example, if
you need to quickly find a function’s inverse given
the function, you could define a dictionary whose keys and values are
functions and then make the dictionary bidirectional (using some
functions from module math, covered in Chapter 15):
inverse = {sin:asin, cos:acos, tan:atan, log:exp} for f in inverse.keys( ): inverse[inverse[f]] ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access