Lecture 1 : Basics of Python

April, 2022 - François HU

Master of Science - EPITA

This lecture is available here: https://curiousml.github.io/

image-2.png

Table of contents

Introduction

  1. Variables
  2. Tests and loops
  3. Functions
  4. Introduction to classes and objects
  5. Modules
  6. Immutable and mutable types
  7. Some pratical tips

Exercices

Introduction

Python’s standard library is very extensive, it contains built-in modules (written in C). If it is your first time using python and jupyter notebook, pleaser refer to the following pages:

In a nutshell, this notebook gives a quick look at some built-in types and functions.

Note that :

1. Variables

As in other languages, variables hold values. In Python, variables do not require forward declaration, all you need to do is provide a variable name and assign it some value. The present section describes some classical variables in python: numeric, boolean, text sequence (aka string) variables. This section also describes some classical container variables:

Note that these variables are built into the interpreter.

1.1. Numbers: integer, float and complex

Let us assign values to variable names and print them (as well as their type)

A more compact way to assign values is:

It's also possible to swap variables in a more compact way:

1.2. Booleans

We can create a boolean by:

using and and or condtions:

Note that a boolean can also be considered as a number:

1.3. Strings

We can assign a text (so called string) to a variable name.

Triple quotes allow to have several lines:

Equivalently, we can add \n to skip a line:

You can also format your string in

1.4. Operations on variables

on numbers

on strings

1.5. Collection of items: List, Set and Dictionary

Let us now see how to store a collection of items (numerical and non numerical). One of the most popular container is list.

List

A list is an ordered collection of items that may have different types. A list is a mutable object and therefore can be modified.

Like string operations, we can concatenate lists, duplicate items of the list or even delete / add some items.

We can also do some indexing and slicing

it is also quite easy to assign some items by specifying the indices.

some other classical methods:

Of course we can also have a list of lists of items

Sets

A set is an unorder collection of unique items. Usual mathematical operations (union, difference) can be performed.

Dictionaries

A dictionary is a table key/value which correponds to a collection of unique keys. Keys can be any immutable type (string, numbers, …).

2. Tests and loops

2.1. Conditional statements

In python, a block of instructions is delimited by indentation. For example the lines included in a ifcondition is written as follows:

just after, we can add an else condition alongside with indented lines

There may be several conditions that follow one another, therefore we need the elif condition

2.2. Loops

There are classically two types of loops:

As for tests, the lines included in a given loop are indented.

The for loop

With the for loop we can run a set of statements, once for each item in a collection of items such as list, dictionary, set etc.

we can use the range function instead of manually specifying the numbers. The syntax for the range function is:

Some useful commands: enumerate and zip.

for loop in a concise manner:

The while loop

With the while loop we can run a set of statements as long as a condition is true.

3. Functions

We can also create functions. A function is a block of code which only runs when it is called. You can pass parameters into a function called (input) arguments and it can return some parameters called (output) results. You can use a triple quote at the beginning of the block if you want to give a documentation for users.

We can take account several arguments in a function

We can also have default values for part (or all) input arguments.

Important remark: non-default argument follows default argument

Thanks to the triple quote, you can use the function "help" on your function. a string that occurs as the first statement in a module, function, class, or method definition is called docstring.

It is possible to check if a parameter is passed with None:

4. Introduction to classes and objects

The present section gives a quick look at the classes and objects. We will dive more into it in other notebooks.

4.1. Definitions

Our main objective is trying to define "complex types" such as

Besides, like lists or dictionaries, we want to have some "descriptions" or "states" associated to these types:

Finally, in addition to these "descriptions", we also want to "modify" their state:

Since, python is an object-oriented programming (OOP) language, it is possible to define this more "complex type" called class

Important remark: Everything in Python is an object

A class is a block of codes (like function, we have indentations) defined as follows :

4.1. Attributes and constructor

When declaring a variable of class Point, the python language executes the __init__ method also called constructor. It allows to define the attributes of the class directly from the parameters or as the result of a calculation or a function. The constructor, like all the other methods, has as its first parameter self which allows access to the attributes and methods of the class.

Attributes are most often declared inside the constructor. More generally attributes can be defined in two ways:

4.2. Methods

A method is a function defined inside a class. It invariably accepts at least one parameter which is self as in the previous example. The following program is equivalent to the first one.

4.3. Instantiating a class

Let us create a new instance of the class and assigns this object to the local variable p.

Print the coordinate of the point p:

One can also easily use the method of the object:

4.4. Operator

Like any variables, we want to have some operations associated to these (same class) objects. As

a = 1
b = 3
print(a + b)

gives you 4, one would want operations for points: for example we except that a point $(1, -1)$ added by a point $(1, 1)$ gives a new point $(2, 0)$. It is possible if we define the operator __add__.

Operators are methods that allow a simpler manipulation of objects. By convention their name start and end with __.

5. Modules

Up to now, we only used the internal libraries of python. Using external libraries is possible and is quite easy to import in python.

5.1. Import an existing module

Let us compute the square root of a number. For that purpose, we can import the library (aka package) numpy (module used for numerical analysis). There are several ways to do it and we show bellow some recommended methods.

method 1: load directly the library

method 2: load the library with a different name (usually a shorter name)

method 3: load only the wanted function from the library

5.2. Create a module

To create a module, store the functions and variables definitions in a Python file. For example, we can create a my_module.py file containing:

image.png

Let us import this module and use the function add:

my_module.py can also be executed as a script. In this case

if __name__ == "__main__": call_me()

will be taken into account and call_me() will be called:

6. Immutable and mutable types

When an object is initiated, it is assigned an unique object ID (we recall that every variables are object instances). Its type cannot be modified but its state can be changed if it is mutable. In summary, after it instantiation, a mutable object can be changed whereas an immutable object cannot be changed. In a nutshell, we listed a (non-exhaustive) immutable and mutable types:

6.1. Immutable types

thanks to the built-in functions id and type (see documentation), we can easily check the id and the type of an object.

Let us create a string variable and copy it to another variable name.

if we change v does u change in consequence ? -> No, immutable objects doesn’t allow modification after creation

6.2. Mutable types

Let us create a list variable and assign it to another variable name.

if we change t does l change in consequence ? -> Yes, mutable objects allow modification after creation, therefore if a list l is assigned with the operator = to t then it merely created a second name to name the same list.

6.3. Avoid modification for mutable types

If we want to copy a list, we need to use the library copy.

7. Some practical tips

What if I struggle too much or if I want to fix an error ?

google it to find at least some clues, recommended: search in stackoverflow

What if I cannot remember a specifi python syntax ?

cheatsheets for python and for specific and well-known packages OR stackoverflow/search engine

What if I want to share my code to someone ? Do I send an email ?

you can, or you can also use tools for sharing whole repertory (usualy in the cloud like DropBox or GoogleDrive)

How to debug my code ?

think of printing/logging within your code in order to find out where we have to debug

How to have a good program ?

write more small functions instead of big functions

Exercices

Exercice 1.

Create the following list with loops:

[['car', 0, 1, 4, 9, 16],
 ['bus', 1, 4, 9, 16, 25],
 ['train', 4, 9, 16, 25, 36],
 ['boat', 9, 16, 25, 36, 49]]

Create a script that prints this list in the following manner:

car      0    1    4    9   16
bus      1    4    9   16   25
train    4    9   16   25   36
boat     9    16  25   36   49

Exercice 2.

For the following list of dictionaries, write a script that add a field registrations which is twice the number of accepted papers.

Exercice 3.

Write a function include, that produces the following results:

>>> l = [0]
>>> include(l, 2)
>>> print(l)
[0, 2]
>>> include(l, "-1")
>>> print(l)
[0, 2, '-1']
>>> include(l)
>>> print(l)
[]

Exercice 4.

Create a module, that contains a function fibonacci(n) computing the $n^{th}$ Fibonacci number. Then create a script using this function.

Exercice 5.

Change the class Point (the toy example bellow) in order to take account a 3rd coordinate z.

class Point:
    """
    Definition of the class "Point"
    """
    def __init__(self, x, y):          
        self.x = x                     
        self.y = y                     
        self.norm = self.compute_norm()

    def compute_norm(self):
        norm = (self.x**2 + self.y**2)**(0.5) 
        return norm

    def __add__(self, another_point) :
         return Point(self.x + another_point.x, self.y + another_point.y)

Then execute the following script.

p1 = Point(1, -1, 1)
p2 = Point(1, 1, 3)
p3 = p1 + p2

print(f"p1 = ({p1.x}, {p1.y}, {p1.z})")
print(f"p2 = ({p2.x}, {p2.y}, {p2.z})")
print(f"p3 = ({p3.x}, {p3.y}, {p3.z})")