Functions and libraries

Programming – Session 2

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

Functions in a programming language

Definition

Definition and use

Functions ensure the readability and reusability of your code:

  • 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

Algorithmic statements involving functions

  • Defining functions (a function takes parameters and returns a value)
  • Calling functions (associate values to parameters and get function’s output)

Functions in a programming language

Defining functions

Defining functions in Python

  • The name of a function, the number and types of its parameters, 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, param_2: int) -> float:

    # Do something
    ...

    # Return something
    return result
# Call the function
res  = func_name(4, 2)

Organizing codes in libraries

Files and modules

Importing modules

  • Functions may be thematically regrouped into separated files (named modules), e.g., mymodule.py
  • To use the functions located in mymodule.py, it has to be imported
# Import the functions from the file
# Alternate method: from mymodule import the_function_i_need
import mymodule

# Use the function
# With alternate method: the_function_i_need()
mymodule.the_function_i_need()
  • When a file is imported it is also executed (to load functions in memory)
  • To avoid some parts to be run when imported, use if __name__ == "__main__":

Organizing codes in libraries

Files and modules (cont)

To keep code organized, it’s good practice to split it into multiple files:

  • 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__":
    # ...

Installing Python modules

Using Pip to install modules

Don’t reinvent the wheel!

  • Python 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
  • e.g., pip install matplotlib

Variables visibility and scope

Variables and functions

Local variables

  • Defined inside a function
  • Not accessible outside it
  • Exists in the body of the function only
# 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)
1 2
(L.8) NameError: name 'a' is not defined

Global variables

  • Defined outside all functions
  • Accessible anywhere using keyword global
  • Exists for the duration of program execution
# Define a global variable
a = 1

# Example function that uses the global variable
def example ():
    global a
    a = 2
    print(a, end=" ")

# See what we got
print(a, end=" ")
example()
print(a)
1 2 2

Recap of the session

Main elements to remember

Functions are reusable, named, blocks of code, that take parameters as input and produce a result


  • Functions help making codes more readable and reusable

  • They need to be defined before being used

  • Coherent collections of functions should be grouped in modules

  • Many modules already exist, and can be installed with pip

  • Local variables exist in the function only

  • Local variables should be favored over global ones

Recap of the session

What’s next?

Practical activity (~5h)

Part 1 (~2h30)

  • Functions
  • Variable visibility
  • Immutable-mutable function parameters

Part 2 (~2h30)

  • Small project using functions
  • Implement a linear regression model

After the session

  • Review the articles of the session
  • Check your understanding with the quiz
  • Complete the practical activity
  • Check next session’s “Before the class” section

Evaluation

  • Prepare for a 30 minute programming test at the beginning of session 3
  • Covers programming sessions 1 and 2 (also review algorithmics session 1)