Functions and libraries

Programming – Session 2

  • Functions in a programming language
  • Variables visibility and scope
  • Organizing codes in libraries
  • Installing Python modules

Functions in a programming language

Definition

Definition and use

Function is a key concept to ensure the readability and reusability of your code. Functions allow to:

  • Factorize (regroup) statements that perform a specific task.
  • Be called on demand anywhere in your code.
  • Be tested independently to then be safely reused and shared.

A function can take parameters and returns a value.

Algorithmic statements involving functions

  • Defining functions
  • Calling functions

Functions in a programming language

Defining functions

Defining functions in Python

The name of a function, the number and types of its arguments, and the type of its returned value(s) is generally called the “signature”, or the “prototype” of a function.

def func_name (param_1: int, param_2: int) -> float:

    """
        This is an example of how to define a function in Python.
        Here, we use type hinting to indicate to the user how they should use it. 
        In:
            * param_1: The first argument to take as an input.
            * param_2: The second argument to take as an input.
        Out:
            * A result computed by the function.
    """

    # Do something
    ...

    # Return something
    return result

Functions in a programming language

Calling a function

Calling a function in Python

Once defined, a function can be called from anywhere just using its name and passing a value for each expected parameter. Values given in a function call are called “actual parameters” or “arguments”.

def func_name (param_1: int = 123, param_2: int = 456) -> float:

    """
        This is an example of how to define a function in Python.
        Here, we use type hinting to indicate to the user how they should use it. 
        In:
            * param_1: The first argument to take as an input.
            * param_2: The second argument to take as an input.
        Out:
            * A result computed by the function.
    """

    # Do something
    ...

    # Return something
    return result



# Call the function
res  = func_name(4, 2)

Variables visibility and scope

Variables and functions

The visibility of a variable determines its lifetime, and two types of visibility are considered in Python, namely local and global variables.

Local variables

Local variables are defined inside a function and not accessible outside it.

# Example function with two local variables
def example (a):
    b = 2
    print(a, b)

# Call it and try to access variables
example(1)
print(a, b) # -> NameError: name 'a' is not defined

Global variables

Global variables are defined outside all functions and accessible anywhere in the code.

# Define a global variable
a = 1

# Example function with a local variable, also named "a"
def example ():
    a = 2
    print(a)

# See what we got
print(a)
example()
print(a)

Organizing codes in libraries

Files and modules

Importing modules

Functions may be thematically regrouped into separated files my_functions.py (named modules). To use the functions located in my_functions.py, it has to be imported:

# Let's assume the file is not in the path
# For instance, assume it's in a directory "my_python_files" in the parent directory containing this script
import sys
import os
sys.path.append(os.path.join("..", "my_python_files"))

# Let's import the "my_functions" module
import my_functions # or from my_functions import func_ext

# Now we can use the function precising the module in which it is
# This can be very practical when multiple modules have functions with the same name
my_functions.funct_ext() # or directly call funct_ext() if the function is explicitly imported

When a file is imported it is also executed.

# This test indicates that we only run this when the file is executed
# directly and not imported as a module
if __name__ == "__main__":
    print("Testing of the module")

Organizing codes in libraries

Files and modules (cont)

To keep code organized, it’s good practice to split it into multiple files. For example:
  • main.py – The main script.
  • functions.py – Contains reusable functions.

The structure of a file such as functions.py should follow the following convention:

"""
    General description of the document contents.
"""

# Needed imports
# ...

# Various functions, well documented.
# ...

# Things to do when running this code directly
if __name__ == "__main__":
    # ...

Organizing codes in libraries

Modules and virtual environments

The Python language comes with a plethora of already defined functions regrouped into thematical modules.
  • Always favor the use of existing (official) modules (Python Standard Library + addional modules).

The python modules installer

The Python Package Index (PyPI) is a repository of software for the Python programming language. PyPI helps you find and install software developed and shared by the Python community, using the pip installer. pip install matplotlib

  • installation of libraries in virtual environments only in GNU/Linux-Unix systems (or forced --break-system-packages)

Recap of the session

What’s next?

Practical activity (~5h)

Activity contents (part 1) (~2h30)

  • Basic and independent exercices on functions, variable visibility, immutable-mutable function parameters

Activity contents (part 2) (~2h30)

  • A very small project using functions
    • implementing a linear regression model

After the session

  • Review the articles of the session
  • Check your understanding with the quiz
  • Complete the practical activity
  • Prepare for the 30 minute programming test at the beginning of the next session
  • Check next session’s “Before the class” section