2.1 Python Functions#
A function is a collection of code that is assigned to a specific name. You have already seen some built-in Python functions, such as print(). Using functions is useful because it allows you to run the same code again without having to type it a second time.
Below are some examples of common built-in Python functions and what they do:
print() Prints input to screen
type() Returns the type of the input
abs() Returns the absolute value of the input
min() Returns the minimum value of the input.
(input could be a list, tuple, etc.)
max() Same as above, but returns the maximum value
sum() Returns the sum of the input
(input could be a list, tuple, etc.)
But the story doesn’t end at built-in functions. You can also write your own functions!
How to write a function#
To write a function, you must first define it. This is done by using the def statement. Then, you name the function and add, in the parentheses, which variables this function takes as an input, followed by a colon. The colon tells Python you are going to define the function body next (the part of the function that actually does the computation). As shown below:
def function_name(input1, input2,...):
:tab: function_body
:tab: ...
:tab: ...
Note that where we have :tab: you should press tab to make sure you have the proper indentation.
The calculate_circle_area(r) function below defines pi as a variable and then computes the area of a circle, which is stored in the variable area. Finally, it uses the return statement to output the area back to you. Once you have defined the function, you can then call it by typing the function name, and the inputs in the parenthesis. For example, calling: print(“Hello World!”), prints the string ”Hello World!”.
Indentation
It is worth noting that the function body should be indented. This is how Python sees what piece of code is inside another code. An indented line of code is a line that starts with whitespace. You can do this by using the tab key on your keyboard.
Attention
Inputs of functions are more often called arguments.
Indentation of code within functions#
Let’s say you’d want to compute the area of a circle, but you don’t want to calculate \(\pi r^2\) every time. Then you can write a couple lines of code to do it for you, and wrap it up into a function, like the one below:
def calculate_circle_area(r):
pi = 3.141592653589793
area = pi*(r**2)
return area
This function is called calculate_circle_area(r), and takes the value r as an argument.
Functions can have multiple arguments, for example:
def calculate_rectangle_area(a, b):
area = a * b
return area
print('Area of my rectangle is', calculate_rectangle_area(4, 6), 'cm^2')
In the cell above, the calculate_rectangle_area(a, b) function takes \(2\) arguments, \(a\) and \(b\).
The built-in function print() takes \(3\) arguments here:
the string ’Area of my rectangle is’, the output of calculate_rectangle_area(a, b), and another string ’cm^2’.
You can also print the results using f-strings:
print(f'Area of my rectangle is {calculate_rectangle_area(4,6)} cm^2.')
Documenting functions#
We have now successfully created a function that computes the area of a circle and the area of a rectangle. You could send this code to fellow students, but maybe they wouldn’t know how to use them. This is where a docstring comes in handy. This is a string specified in the beginning of the function body which states information about the function. A lot of built-in Python functions also have docstrings, which is really useful when you’re trying to understand how to use a function. Try it out for yourself, add some docstring below.
def calculate_circle_area(r):
'''PUT YOUR DOCSTRING HERE!'''
pi_circle = 3.141592653589793
area = pi_circle*(r**2)
return area
As you can see, nothing happened. But, if we now call the function like this:
calculate_circle_area?
or:
help(calculate_circle_area)
we should see the description (docstring) of the function. Try yourself below:
# use this line to check the the docstring of the above function, use one of the above methods
...
When to write or use a function?#
You can use functions in your code when you have a specific piece of code that you need to use multiple times (e.g.: plotting something).
Often you will find you want to use an output from a function later on. To do this, you can assign the value returned by a function to a variable. Let’s say I want to use the area of a circle in a later calculation. Then you can store it in a variable like this:
Circle_Area = calculate_circle_area(4)
# here, we stored the area of a circle that has a radius 4
# in the variable 'Circle_Area'
calculate_circle_area(4) is now stored in the variable Circle_Area. See below:print(Circle_Area)
We can see that the value was indeed stored.
Attention
Variables that are defined inside a function body can NOT be used outside of the function. These variables are called local variables.
Take the variable pi_circle that we defined in the function calculate_circle_area(). If we try to print it:
print(pi_circle)
See, it doesn’t work! The error you get: name ‘pi_circle’ is not defined, means that you tried to call a variable that does not exist.
Additional study material
Official Python Documentation - https://docs.python.org/3/tutorial/controlflow.html#defining-functions
Think Python (2nd ed.) - Chapters 3, 6, and 16