V.
FUNCTIONS
Module 3 - Python
¬ Index
1. Functions 3
1.1 The concept of functions in Python 3
1.2 How to use functions 4
1.3 Arguments and parameters 9
1.4 Python built-in functions 15
1.5 Good practices with functions 18
Python
1. Functions
1.1 The concept of functions in Python
To make a software application modular, we use functions. These are blocks of code that
perform specific tasks and can be called upon from another part of the program.
For example, the different tasks that need to be performed in the software that is being developed
can be implemented with functions. From the main function, you can call them when required
to execute the task that is associated with them.
Figure 1
3
1.2 How to use functions
Figure 2
Figure 3
Functions are snippets of code that can be executed multiple times. They can receive and
return information to communicate with the main process or main function, called main:
Figure 4
4
Python
Python is a sequential programming language, which means it executes the lines of code from
the first to the N, one at a time. But functions behave differently, their lines of code are only
executed when the function is called. To see it in action, let’s trace the program, which will
show us the sequence of executions of our program:
Figure 5
In functions, it’s important to know what is the scope of a variable, so what scope or visibility
does that variable have. Keep in mind that a variable declared in a function doesn’t exist
outside of it.
Figure 6
However, a variable declared outside the function (at the same level), is accessible from the
function, these variables are known as global variables:
Figure 7
5
Whenever we declare the variable before execution, we can access it from within:
Figure 8
And in the event that we declare a variable in the function again, a copy of it will be created
that will only work within the function. Therefore, we cannot modify an external variable within
a function:
Figure 9
In order to modify an external variable within a function, we must indicate that it’s global, with
the global statement, as follows:
Figure 10
6
Python
The above example would be the same as:
Figure 11
To communicate with the outside, functions can return values to the main process thanks to
the return statement. When a value is returned, the execution of the function will end:
Figure 12
The logical thing to do is store what the function returns in variables, so we can use these
values later:
Figure 13
The returned values are treated as direct literal values of the returned data type, so it’s important
to know the types of data we are handling:
Figure 14
7
This includes any type of collection:
Figure 15
Another interesting feature is the ability to return multiple values separated by commas, which
is known as multiple return:
Figure 16
These values are treated as an immutable tuple and can be reassigned to different variables:
Figure 17
8
Python
1.3 Arguments and parameters
Figura 18
Figura 19
To communicate with the outside, not only can functions return values to the main process
thanks to the return statement, but they can also receive information. In the definition of a
function, the values that are received are called parameters, and in the call, they are passed
as arguments.
Figure 20
9
So, we can pass two values to a function:
Figure 21
And we can pass variables as arguments:
Figure 22
When we call a function that has defined parameters, if we do not pass the arguments correctly
it will cause an error:
Figure 23
If we call it with an incorrect number of arguments, it will also cause an error:
Figure 24
10
Python
To solve the problem of making calls without arguments, we can assign null default values, or
any default value we want, to the parameters. In this way, we can run a check before executing
the code of the function, as seen below:
Figure 25
We can pass parameters to a function in two ways, by value or reference. Passing by value
creates a local copy of the variable within the function, so changes made within the function will
not affect the value outside the function. While in passing by reference, the variable is handled
directly, so the changes made within the function will also affect it outside. Traditionally, simple
types (integers, floats, strings, logical) are automatically passed by value, and compounds
(lists, dictionaries, sets) by reference.
Here is an example of passing parameters by value:
Figure 26
11
And here is an example of passing parameters by reference:
Figure 27
In Python, we cannot select the way to pass parameters to a function by value or by reference,
so a ‘trick’ to modify the simple types, is to return them modified and re-assign them:
Figure 28
In the case of compound types, by passing them as parameters by reference, we can avoid
modifying them by passing a copy:
Figure 29
We may not know in advance how many elements we are going to pass to a function. In this
case, we can use the indeterminate parameters by position and by name.
12
Python
To receive an indeterminate number of parameters by position, we must create a dynamic list
of arguments (a tuple actually):
Figure 30
To receive an indeterminate number of parameters by name (key-value), we must create a
dynamic dictionary of arguments:
Figure 31
If we want to accept both types of parameters simultaneously, then we must create a dynamic
collection for each:
Figure 32
13
Recursive functions are those that call themselves during their own execution. They work in
a similar way to iterations, and we must take care of planning the moment when a recursive
function stops being called, or we will have an infinite recursive function. They are often used
to break a task down into simpler subtasks so that it’s easier to address the problem and fix it.
A simple example, with no return, is the countdown to zero from a number:
Figure 33
And an example with return, is the factorial of a number, which corresponds to the product of
all numbers from 1 to the number itself:
Figure 34
14
Python
1.4 Python built-in functions
Figure 35
These are functions provided by the Python language itself. The complete list can be found
here: https://docs.python.org/3/library/functions.html Let’s look at some examples of these
built-in functions:
To transform a string to an integer, we use the int() function: (if it’s not possible, you will get
an error)
Figure 36
To transform a string to a floating-point number we use float(): (if it’s not possible, you will
get an error)
Figure 37
15
To transform any value to a string, we use str():
Figure 38
To covert an integer to binary, we use bin():
Figure 39
To covert an integer to hexadecimal, we use hex():
Figure 40
To convert a decimal value to an integer, we use int():
Figure 41
To get the absolute value of a number, we use abs():
Figure 42
16
Python
To round a float to an integer, we use round(): (down if it’s less than .5, up if it’s greater than
or equal to .5)
Figure 43
To evaluate a string as an expression, we use eval(): (accepts variables if defined above)
Figure 44
To get the length of a collection or string, we use len():
Figure 45
To invoke the Python interpreter help menu, we use help():
Figure 46
17
How to access the functions documents using help():
Figure 47
1.5 Good practices with functions
Here are some guidelines to follow to program useful and re-usable functions:
¬ Program small functions that focus on specific problems.
¬ When designing a function, think about how it can be reused.
¬ Document the functions to be able to access their description using the help() function.
With these tips, we will achieve:
¬ A more modular code.
¬ A more readable code.
¬ An easier code to test.
¬ Easier to solve problems.
18
Python
An example of Python functions is converting a value from Fahrenheit degrees to Celsius
degrees:
Figure 48
And here is another example with several functions that perform some arithmetic operations
on a given operand:
Figure 49
19