# Functions, Modules and Libraries¶

## Functions¶

Image that you need to write a program in Python which can calculate the final grades earned by students who have followed a university course. Such grades are normally calculated using a fixed formula (e.g. a mid-term assignment which counts for 40% and a final exam which counts for 60%). To calculate the final grades, this formula needs to be applied repeatedly with different values. In such a situation, it would be quite inefficient if you simply repeated the code that is needed for every single student. In most programming languages, fortunately, it is also possible to reuse fragments of code by defining these as functions.

A function is essentially a set of statements which can be addressed collectively via a single name. Python has a number of in-built functions, such as print() or split(). As you have seen, such functions represent certain actions. To have these actions executed, you need to refer to the names of these functions in your programs.

Next to working with in-built functions, it is also possible to write your own functions. Working with functions can often be very effective. It enables you to decompose specific problem into smaller sub-problems and into units which can be reused as often as needed. As illustrated in the code below, functions can be created using the ‘def’ keyword.

In [ ]:
def calculateFinalMark( midTerm, exam ):
finalMark = 0.4 * midTerm
finalMark += 0.6 * exam
return finalMark

print( str( calculateFinalMark( 8 , 9 ) ))
print( str( calculateFinalMark( 4 , 10 ) ))
print( str( calculateFinalMark( 6 , 7 ) ))


The first four lines of the code above define the function calculateFinalMark(). The 'def' keyword needs to be followed by the name of the function, which you can specify yourself. The name of the function also needs to end in a set of parentheses. Within these parentheses, you can optionally mention the values the function should operate on. These values mentioned within the parentheses are called the parameters of the function. If there are two or more parameters, these need to be separated by commas. In the example above, a certain calculation is carried out within the function, using the parameters that are supplied, and the result of this calculation is mentioned after the keyword ‘return’.

Once the function has been defined, it can be used, or invoked, on other locations in your program. The print statements on the final three lines will show the result of the calculation that is returned by the function, using the values that are mentioned within the parentheses as a basis.

## Classes¶

Python is based on a programming paradigm which is known as object-oriented programming. This paradigm, in short, involves an organisation in which variables and functions which are closely related can be brought together in structure known as a class. In the example below, the variables named ‘title’ and ‘isbn’, and the function named ‘describe’ are brought together in a class named ‘Book’.

A class can also be instantiated. An instance of a class is called an object, and this object can be given a new name. For this newly created object, all the variables and all the functions which are defined in the class can also be accessed, by appending the names of the variables or functions to the dot following the object name. This notation is called the ‘period syntax’. Functions defined within classes are referred to as methods. A class thus functions as a blueprint or as a template for new types of objects.

In [ ]:
class Book:
def __init__(self, title, isbn ):
self.title = title
self.isbn = isbn

def describe(self):
print("Title: " + self.title)
print("ISBN: " + str(self.isbn))

title1 = Book("A Room with a View", "978-1420925432")
title1.describe()


In the code above, a new object is created based on the class Book, named title1. In the definition of this particular class, it was specified that the title and the ISBN always needs to be provided upon the initiation of a Book object. Once the class Book has been instantiated in this way, the object based on the class specifications can make use of all the methods of the class. The method describe(), for instance, simply prints the values that have been assigned to the object.

## Modules, packages and libraries¶

A module, in short, is a file with code that you can reuse across different programs. The term 'Python library' generally refers to a collection of related modules. These libraries, in turn, are mostly distributed as packages. Once installed, a Python package is a directory on your computer which contains a library. This library is usually a collection of one or more Python modules.

To use a library within your program, you need to import it first via the ‘import’ keyword. If you want to use the library named ‘os’, for instance, you need to use the following command:

In [ ]:
import os


This 'os' library will be discussed in more detail in the section focusing on working with files and directories. Once imported, all the functions and the classes that are defined within this library can be used via the period syntax. The function 'listdir()', for instance, can be invoked using the code below:

In [ ]:
files = os.listdir('Corpus')


Alternatively, it is also possible to import individual functions from a module.

In [ ]:
from os import listdir


This second way of importing code has the advantage that it is no longer necessary to use the period syntax. The function can then be used without referencing the name of the module:

In [ ]:
files = listdir('Corpus')