In this notebook, we introduce a modularization concept known as functions. Functions promote code reuse by encapsulating a particular set of program statements into a single entity. When you have completed this notebook, you will be able to create and apply user-defined functions.
The Python language supports the creation and application of user-defined functions, which can simplify program development by promoting code reuse (in a similar manner as importing packages developed by others, but in this case, you are the code provider and consumer). In Python, a function is actually an object, like everything else, and they can thus be created and passed dynamically like any other data type.
A Python function is defined by using the def
keyword, followed by the function name. After the function name is a set of matching parentheses that enclose any arguments to the function. A colon character follows the closing parenthesis, which signifies the start of the code block that provides the function implementation, which is known as the function body. As a simple example, the following function takes no arguments and simply prints a standard message:
def hello():
print("Hello World!")
This function is called in a Python program by simply using its name followed by the parentheses, hello()
, which will print out Hello World!
to the display.
Student Exercise
In the empty Code cell below, create a simple function that takes no arguments and prints the message Success!
A standard practice is to employ a docstring, or documentation string, comment immediately after the function definition line to provide documentation for the function. A docstring comment is enclosed in triple-quotes, for example:
"""Here is our demonstration docstring comment.
The text can span multiple lines, until
the closing set of quotes is employed.
"""
The Python interpreter will by default use this docstring as the official function documentation, which typically is accessed by using the built-in help()
function. This is demonstrated in the following two code blocks, where we define and call this function, and subsequently access the documentation.
def hello():
"""Display a welcome message to the user."""
print("Hello World!")
hello()
help(hello)
A function can accept zero or more arguments by simply listing the argument names between the parentheses. These argument names are the names you use to access the values contained in these arguments within the function body. For example, we can modify the original hello
function to take a name
argument that is used when printing out a welcome message:
def hello(name):
"""Display a welcome message to the user."""
print("Hello {0}".format(name))
When called with an argument Alexander
, this function will print Hello Alexander
.
# Create our first function that takes an argument
def hello(name):
"""Display a welcome message to the user."""
print("Hello {0}".format(name))
hello('Alexander')
Functions can take multiple arguments, in which case the different arguments are simply separated by commas between the parentheses. A function can also take data structures as arguments, like lists or tuples.
def hellolist(names, text):
"""
Display a welcome message to the user(s) listed in the names,
which is assumed to be a list.
"""
for name in names:
print("Hello {0}, {1}".format(name, text))
If this function is called as hellolist(['Alex', 'Joe', 'Jane'], "welcome to class.")
, the following output is displayed:
Hello Alex, welcome to class.
Hello Joe, welcome to class.
Hello Jane, welcome to class.
In some cases, a function accepts one or more arguments that often have default values. Python supports default arguments that enable a Python programmer to specify a default value for an argument, which can be overridden if the user supplies a specific value. A default argument is specified by simply including an equal sign and the default value after a specific argument, like text = ' welcome to class.'
. With this default argument for the hellolist
function, we could leave off the second argument if desired.
Default arguments are often used in functions that are part of large packages, like numpy
or matplotlib
to simplify their use. New users can quickly call the functions, while advanced users can achieve more control of the function by specifying additional arguments explicitly.
def hellolist(names, text):
"""
Display a welcome message to the user(s) listed in the names,
which is assumed to be a list.
"""
# Below we use an 'f-string' to simply display the desired result.
for name in names:
print(f"Hello {name}, {text}")
hellolist(['Alex', 'Joe', 'Jane'], "welcome to class.")
One last aspect of function arguments is that when a function is called, the argument names listed in the function definition can be explicitly specified, along with the values they should take when the function is called. This type of function call is said to be using keyword arguments. When using keyword arguments, the order of the arguments listed in the function call is arbitrary and does not need to explicitly match the argument order listed in the function definition. For example, we could call the hellolist function:
hellolist(text=' welcome to class', names = ['Alex', 'Joe', 'Jane'])
A function can return values by using the return
keyword. Single values are returned as the type of the value, while multiple values are returned as a tuple of values. These two cases are demonstrated in the following sample code:
def hello2():
return "Hello World!"
def hello3(name):
return "Hello, ", name
Calling the first function in this sample code as msg = hello2()
will assign the string Hello World!
to the msg
variable, while calling the second of these functions as msg = hello3()
will assign the tuple ('Hello', name)
to the msg
variable. Note that for the hello3
function, the argument is not required, as written, to be a string; therefore, the return tuple will have a string as the first element and the second element will be the same type as the argument name
.
Note, when returning multiple values as a tuple, we can either enclose the values in parentheses, or simply separate them with commas as shown in the example.
Student Exercise
In the empty Code cell below, create a simple function that takes a numerical argument and returns the argument multiplied by 10. Demonstrate your funtion works by displaying the result of the function on the integer 10.
Python also supports the ability to create unnamed functions, which are short functions that are defined and used in place. An unnamed function in Python is called a lambda
function and is defined by using the lambda
keyword. lambda functions are often used in comprehensions or in function calls, when an argument expects a function. For example, we can create a lambda
function that takes multiple arguments and assigns to an arbitrary variable for later invocation:
f = lambda x, y: x**2 + y**3
print(f(3, 4))
73
We can use a lambda function to create a list comprehension, either implicitly with a defined function like the previous example, or explicitly with an in-place lambda
function. In either case, we can use the map
function to apply the function to a range of input arguments.
[x for x in map(lambda x: (3*x**2 + 2*x + 4), range(-3,4))]
Will create the following list:
[25, 12, 5, 4, 9, 20, 37]
The following links are to additional documentation that you might find helpful in learning this material. Reading these web-accessible documents is completely optional.
© 2017: Robert J. Brunner at the University of Illinois.
This notebook is released under the Creative Commons license CC BY-NC-SA 4.0. Any reproduction, adaptation, distribution, dissemination or making available of this notebook for commercial use is not allowed unless authorized in writing by the copyright holder.