1.4. 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 screentype()
: Returns the type of the inputabs()
: Returns the absolute value of the inputmin()
: Returns the minimum value of the input. (input could be a list, tuple, etc.)max()
: Same as above, but returns the maximum valuesum()
: 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!
1.4.1. 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,...):
function_body
...
...
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.
Note
Inputs of functions are more often called arguments.
1.4.2. 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\) the entire 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')
Area of my rectangle is 24 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:
the string ’Area of my rectangle is’
, the output of calculate_rectangle_area(a, b)
, and another string ’cm^2’
.
There are better ways to use the built-in print()
function when writing long sentences that have variables in between. For example:
print('Area of my rectangle is {} cm^2 and the area of my circle is {} cm^2'. \
format(calculate_rectangle_area(4,6), calculate_circle_area(4)))
Area of my rectangle is 24 cm^2 and the area of my circle is 50.26548245743669 cm^2
If a line in your code extends the width of your page, you can use a \ at the point where you want to break the line, as shown above.
Note that the variables (separated by commas) called inside the .format()
will appear, in order, where the { } are located.
Furthermore, you can also format how you want the numbers to appear, as shown below:
print('Area of my rectangle is {:.5f} cm^2 and the area of my circle is {:.2f} cm^2'. \
format(calculate_rectangle_area(4,6), calculate_circle_area(4)))
Area of my rectangle is 24.00000 cm^2 and the area of my circle is 50.27 cm^2
Where the :.5f
states that you want to print that variable with \(5\) decimal numbers. Similarly, :.2f
rounds the number to \(2\) decimal numbers. More information on this in Section 3.1, in Notebook 3.
1.4.3. 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.
Add a description to the calculate_circle_area(r)
function below, as a docstring.
def calculate_circle_area(r):
'''This function calculate the area of a circle with radius r '''
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:
help(calculate_circle_area)
Help on function calculate_circle_area in module __main__:
calculate_circle_area(r)
This function calculate the area of a circle with radius r
Now this isn’t of much use when you work on your own code, unless you are very forgetful or have to write large programs. But if you work using other people’s code, this is really useful, as it helps you figure out how to use each function.
1.4.3.1. 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 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:
We stored the area of a circle that has a radius 4 in the variable Circle_Area
Circle_Area = calculate_circle_area(4)
Nothing happens, but the value of calculate_circle_area(4)
is now stored in the variable Circle_Area
. See below:
print(Circle_Area)
50.26548245743669
We can see that the value was indeed stored.
Warning
Variables that are defined inside a function body can NOT be called from 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)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[52], line 1
----> 1 print(pi_circle)
NameError: name 'pi_circle' is not defined
See, it doesn’t work!
The error you get: NameError: name ‘pi_circle’ is not defined
, means that you tried to call a variable that does not exist.
1.4.4. Additional study material:#
Official Python Documentation - https://docs.python.org/3/tutorial/introduction.html
Think Python (2nd ed.) - Section 2
Official Python Documentation - https://docs.python.org/3/library/operator.html
Think Python (2nd ed.) - Sections 2 and 5
Official Python Documentation - https://docs.python.org/3/tutorial/controlflow.html#defining-functions
Think Python (2nd ed.) - Sections 3, 6 and 16
1.4.4.1. After this Notebook you should be able to:#
understand why you need to learn Python
create and re-assign new variables
determine the type of a variable using
type()
slice strings
perform simple math using arithmetic operators
compare two or more variables
check if a value, or element, exists in an object
define a function, including its docstring