0% found this document useful (0 votes)
2 views18 pages

TP0 Python Refresher

The document is a Python refresher that covers the fundamentals of Python programming, its advantages and drawbacks compared to other languages, and useful tools for installation and usage. It includes sections on basic programming concepts, data structures, functions, and libraries such as NumPy for numerical operations and Matplotlib for plotting. The document serves as a comprehensive guide for beginners and those looking to strengthen their Python skills in data science and machine learning.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views18 pages

TP0 Python Refresher

The document is a Python refresher that covers the fundamentals of Python programming, its advantages and drawbacks compared to other languages, and useful tools for installation and usage. It includes sections on basic programming concepts, data structures, functions, and libraries such as NumPy for numerical operations and Matplotlib for plotting. The document serves as a comprehensive guide for beginners and those looking to strengthen their Python skills in data science and machine learning.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

TP0_python_refresher

April 14, 2026

1 TP 0: Python refresher
1.1 Recalls
1.1.1 Python language
What is Python and why ?
• Python is fundamental language programming to data science and machine learning, as well
as an everexpanding list of areas such as cyber-security, and web programming.
• It is used to prototype, design, simulate, and test easily because Python provides an inherently
easy and incremental development cycle and offers access to a large base of reliable open-source
codes, and a hierarchical compartmentalized design philosophy.
• It is an interpreted language. This means that Python codes run on a Python virtual machine
that provides a layer of abstraction between the code and the platform it runs on, thus making
codes portable across different platforms (Windows laptop, Linux-based supercomputer, or a
mobile phone).
• Python is a dynamically typed language, which means that the interpreter itself figures out
the representative types (e.g., floats, integers) interactively or at run-time. Unlike Fortran
or C/C++ that have compilers that study the code from beginning to end, perform many
compiler-level optimizations, link intimately with the existing libraries on a specific platform,
and then create an executable that is henceforth liberated from the compiler.
• Python facilitates maintainability of scientific codes because Python syntax is clean, free of
semi-colon litter and other visual distractions that makes code hard to read and easy to
obfuscate.

Comparison with other languages

Python Advantages:
• Easy to learn and easy to read.
• Gives access to many powerful libraries.
• Quick to write usable (and reusable) code.
• Rich documentation and help available from the Python community.
Drawbacks: * Slow compared to C/C++. * Code can easily become messy for big projects. * Less
packages than Matlab and R in their own domain of research.

R Advantages:
• Suitable for statistics and maching learning.

1
• Open Source.
• Lots of packages.
Drawbacks: * Much slower than other programming languages such as MATLAB and Python. *
Dedicated to a single domain (statistics).

Matlab Advantages:
• Allows complex simulations.
• Easy to learn, easy to write.
• Very powerful system for data and robotic.
Drawbacks: * Not free and expensive. * Parallel computation not available in the base version. *
Not easy to share your code.

C/C++ Advantages:
• Very fast execution (optimized compilers).
• Access to lots of libraries.
• Potential for high performance.
Drawbacks: * Hard to learn. * Writing programs takes a long time. * Third-party libraries are
often difficult to use.

Usefull tools

Installation The easiest way to get started is to download the freely available Anaconda distri-
bution provided by Anaconda, which is available for all of the major platforms.
On Linux, even though most of the toolchain is available via the built-in Linux package manager,
it is still better to install the Anaconda distribution because it provides its own powerful package
manager (i.e., conda) that can keep track of changes in the software dependencies of the packages
that it supports.
Note that if you do not have administrator privileges, there is also a corresponding Miniconda
distribution that does not require these privileges. Regardless of your platform.
We recommend Python version 3.7 or better.

Usage There are several ways to write and execute Python scripts. The main ones are detailed
below.
Jupyter Notebook
Jupyter Notebook is an open-source web application that allows data scientists to create and share
documents that integrate live code, equations, computational output, visualizations, and other
multimedia resources, along with explanatory text in a single document.
You can use Jupyter Notebooks for all sorts of data science tasks including data cleaning and trans-
formation, numerical simulation, exploratory data analysis, data visualization, statistical modeling,
machine learning, deep learning, and much more.

2
Jupyter is a way of working with Python inside a virtual “notebook” and is growing in popularity
with data scientists in large part due to its flexibility. It gives you a way to combine code, images,
plots, comments, etc., in alignment with the step of the “data science process.”
Pycharm
Pycharm is the most popular IDE used for coding in Python. It can be used for code analysis,
debugging, and testing, among other things. PyCharm Community Edition is simply a free variant
of the professional PyCharm application. This version is great for beginners.
Spyder
Spyder is also an IDE that offers both an editor and a Python shell. It is an efficient tool for
developing and testing codes. In particular feature, it enables to run only part of the script while
keeping the previous results (variable states) in memory.

Getting help
• Official documentation: [Link]
• Book: Python for Probability, Statistics, and Machine Learning
• Most usefull libraries: numpy, scipy, pandas, scikit-learn, statsmodels.
• Forums: [Link]

1.1.2 Basics of python programming


Numbers
[1]: a = 5 # Integer
print(a)
type(a)

[1]: int

[2]: b = -a # Integer
print(b)
type(b)

-5

[2]: int

[3]: c = 7.2 # float


print(c)
type(c)

7.2

[3]: float

3
[4]: d = -1.2 + 3j # Complex
print(d)
print([Link], [Link])
type(d)

(-1.2+3j)
-1.2 3.0

[4]: complex

[5]: t = True # Boolean


f = False # Boolean
type(t)

[5]: bool

[6]: print(t and f)

False

[7]: print(t or f)

True

[8]: print(a == 5)

True

[9]: print(a == b)

False

[10]: print(int(t), int(f)) # cast Boolean to int

1 0

Operations
[11]: print(a + c) # Addition

12.2

[12]: print(a - c) # Substraction

-2.2

[13]: print(a * c) # Multiplication

36.0

4
[14]: print(a / c) # Division

0.6944444444444444

[15]: print(36 // 5) # Integer division

[16]: print(10**3) # Power

1000

[17]: print(10%4) # Modulo

Data structures Strings


Strings are immutable objects (they cannot be modified), that can be defined as follows:

[14]: s1 = "Machine learning"


s2 = 'Machine learning'
print(type(s1)==type(s2))
type(s1)

True

[14]: str

[4]: text1 = """This a


machine learning
cours"""
print(text1) # Triple quotes allow having several lines

This a
machine learning
cours

[5]: print("This is a " + s1 + " Course") # Concatenation

This is a s1 Course

[ ]:

[16]: print((s1+ " ")*3) # Duplication

Machine learning Machine learning Machine learning

5
[11]: print(f"This is a {s1} course") # Formatting
print("This is a {} course".format(s1))

This is a Machine learning course


This is a Machine learning course

[26]: age = 56
name = "Robert"
print("{} is {} years old".format(name, age))

Robert is 56 years old

[27]: print("The squared root of {} is {:.3f}".format(10, 2.23606797749979))


print("The squared root of {} is {:.3e}".format(10, 2.23606797749979))

The squared root of 10 is 2.236


The squared root of 10 is 2.236e+00

Lists A list is an ordered collection of items, that may have different types. A list is a mutable
object and can thus be modified.
[18]: l1 = [5, 6, 4, 3, 7]
l2 = ["Yellow", "Orange", "Red", "Blue", "Green"]
l3 = [5, "Yellow", 6, "Red", 3.4, "Robert"]
print(l1)
print(l2)
print(l3)

[5, 6, 4, 3, 7]
['Yellow', 'Orange', 'Red', 'Blue', 'Green']
[5, 'Yellow', 6, 'Red', 3.4, 'Robert']

[29]: print(l3[0]) # First element


print(l3[1]) # Second element
print(l3[-1]) # Last element

5
Yellow
Robert

[30]: print(l3[:3]) # First three elements


print(l3[-3:]) # Last three elements
print(l3[1:5]) # Sublist
print(l3[::-1]) # Reverse

[5, 'Yellow', 6]
['Red', 3.4, 'Robert']

6
['Yellow', 6, 'Red', 3.4]
['Robert', 3.4, 'Red', 6, 'Yellow', 5]

[31]: print(l1+l2) # Concatenation

[5, 6, 4, 3, 7, 'Yellow', 'Orange', 'Red', 'Blue', 'Green']


1
2 <! img scr=“path/[Link]”>

[21]: print("l1 = ", l1)


[Link]([2, 5]) # Add element to the end of the list
print("new l1", l1)

l1 = [5, 6, 4, 3, 7]
new l1 [5, 6, 4, 3, 7, [2, 5]]

[22]: l1[-1]

[22]: [2, 5]

[20]: [Link]()
l1

[20]: [5, 6, 4, 3, 7]

[23]: print(a == 5)
print(3 in l1) # Presence
print(2 in l1)

True
True
False

[36]: len(l1) # Length

[36]: 5

Tuple Roughly speaking, a tuple is an immutable list (it cannot be changed). It can be defined
as follows:
[37]: t = (-1,1)
print(t)
type(t)

(-1, 1)

[37]: tuple

7
[38]: t+=(0,) # Adding an element to a tuple
t

[38]: (-1, 1, 0)

[26]: t = (1, 5 , 9)
e1, e2, _ = t # Unpacking
print(e1, e2)

1 5

Dictionnaries A dictionary is a table key/value. Keys can be any immutable type (string,
numbers, …).

[45]: d1 = {"Name": "Robert", "Age": 64}


print(d1)

{'Name': 'Robert', 'Age': 64}

[41]: print([Link]()) # Keys

dict_keys(['Name', 'Age'])

[42]: print([Link]()) # Values

dict_values(['Robert', 64])

[43]: print(d1["Name"])
print(d1["Age"])

Robert
64

[27]: d2 = dict() # Define an empty dictionnary


d2["x"] = [-10,3] # Add elements
d2["y"] = [4,6]
print(d2)

{'x': [-10, 3], 'y': [4, 6]}

[45]: print("x" in d1) # Presence


print("x" in d2)

False
True

Conditions

8
[39]: x = 4
y = 1

print("x is", end = " ")


if x < y:
print("is less than y")
print("je suis in")
elif x > y:
print("is greater than y")
else:
print("is equal to y")

x is is greater than y

Loops For loop


[40]: for i in range(5):
print(i, end=" ") # end=" " is used to print in one line

0 1 2 3 4

[41]: l2 = ["Yellow", "Orange", "Red", "Blue", "Green"]


for e in l2:
print(e, end=" ")

Yellow Orange Red Blue Green

[43]: for i, e in enumerate(l2):


print("item {}: {}".format(i,e))

item 0: Yellow
item 1: Orange
item 2: Red
item 3: Blue
item 4: Green

[42]: l2

[42]: ['Yellow', 'Orange', 'Red', 'Blue', 'Green']

[46]: for key, value in [Link]():


print(key, ":", value)

Name : Robert
Age : 64

[48]: l1 = [5, 6, 4, 3, 7]
l4 = [e**2 for e in l1] # list comprehensions

9
l5 = [e for e in l1 if e%2!=0 ]
print(l1)
print(l4)
print(l5)

[5, 6, 4, 3, 7]
[25, 36, 16, 9, 49]
[5, 3, 7]

[ ]: l4 = [e**2 for e in l1] # list comprehensions


l4= []
for e in l1:
[Link](e**2)

While loop
[ ]: v = 0
while v<10:
print(v, end=" ")
v += 1

[ ]: v = 0
while v<10:
print(v, end=" ")
v += 1
if v%5==0:
break

Functions
[ ]: def my_first_function():
print("This is a function")
my_first_function()

[51]: def add(x,y):


return(x+y)
add(6,8)

[51]: 14

Numpy NumPy is a Python library used for working with arrays. It also has functions for
working in domain of linear algebra, fourier transform, and matrices.
[47]: import numpy as np # Load the numpy module with the name np
from numpy import random # Load random from numpy
from numpy import * # Import evrything from numpy

10
[48]: a = [Link]([4.4,6.8,7.2])
print(a)
print([Link])
type(a)

[4.4 6.8 7.2]


(3,)

[48]: [Link]

[49]: print([Link](a)) # Functions


print([Link](a))
print([Link](a))

[-0.95160207 0.49411335 0.79366786]


[ 81.45086866 897.84729165 1339.43076439]
[1.48160454 1.91692261 1.97408103]

1.1.3 Plotting
Two popular libraries are used for visualizations: * Matplotlib * Seaborn
[ ]: import [Link] as plt
import seaborn as sns

x = [Link](0,10,1000)
y1 = [Link](x)

[Link](x, y1, label="sin") # plot y as a function of x, label designs the␣


↪label of the legend

[Link]("x") # set the name of the x axis


[Link]("y") # set the name of the y axis
[Link]("Sine curve")
[Link]() # Add the legend
[Link]() # Add the grid

[ ]: [Link](figsize=(6,4)) # Changing the figure size


[Link](x, y1, color="r", linestyle="--", linewidth=0.8, label="sin") #␣
↪Changing the color, the linestyle and the line width

[Link]("x")
[Link]("y")
[Link]("Sine curve")
[Link]()
[Link]()

[ ]: fig, ax = [Link]() # Create a figure with a single Axes object


[Link](x, y1, label="sin")
ax.set_xlabel("x") # set the name of the x axis

11
ax.set_ylabel("y") # set the name of the y axis
ax.set_title("Sine curve")
[Link]() # Add the legend
[Link]() # Add the grid

[ ]: y2 = [Link](x)
fig, ax = [Link]()
[Link](x, y1, label="sin")
[Link](x, y2, label="cos") # Plot the cosine curve in the same axis
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Sine and cosine curves")
[Link]()
[Link]()

[ ]: x=[Link](0,2*[Link],1000)
y1 = [Link](x)
y2 = [Link](x)
fig, ax = [Link]()
[Link](x, y1, linestyle="--", color="b", label="sin") # Customize the sine␣
↪curve

[Link](x, y2, linestyle="--", color="r", label="cos") # Customize the cosine␣


↪curve

ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_xticks([[Link] * t for t in [0,0.5,1,1.5,2]],[r'$0$', r'$\frac{\pi}{2}$',␣
↪r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'] ) # Customize the x axis

ax.set_title("Sine and cosine curves")


[Link](loc="upper center", shadow=True) # Customize the legend
[Link]() # Customize the grid
[Link]("my_fig.png", dpi=150, bbox_inches="tight", transparent=True) #␣
↪Saving figures

[ ]: fig, ax = [Link](1, 2, sharex=True, sharey=True, figsize=(8, 4)) #␣


↪Subplot with 1 row, 2 columns

# First subplot
ax[0].plot(x, y1, color='blue')
ax[0].set_xlabel("x")
ax[0].set_ylabel("y")
ax[0].set_title("Sine curve")

# Second item
ax[1].plot(x, y2, color='red')
ax[1].set_xlabel("x")
ax[1].set_ylabel("y")
ax[1].set_title("Cosine curve");

12
[ ]: fig, ax = [Link](2, 1, sharex=True, sharey=True, figsize=(4, 8)) #␣
↪Subplot with 1 row, 2 columns

# First subplot
ax[0].plot(x, y1, color='blue')
ax[0].set_xlabel("x")
ax[0].set_ylabel("y")
ax[0].set_title("Sine curve")

# Second item
ax[1].plot(x, y2, color='red')
ax[1].set_xlabel("x")
ax[1].set_ylabel("y")
ax[1].set_title("Cosine curve");

1.1.4 Oriented object programming


Definition In Python, object-oriented Programming (OOPs) is a programming paradigm that
uses objects and classes in programming. The main concept of OOPs is to bind the data and the
functions that work on that together as a single unit so that no other part of the code can access
this data.
A class is a collection of objects. A class contains the blueprints or the prototype from which the
objects are being created. It is a logical entity that contains some attributes and methods.

Instanciating a class Let’s consider for example the class [Link]. We instanciate the
[Link] by calling the constructor of the class with a set of parameters:
[50]: import numpy as np

arr= [Link]([9,5,7,0], dtype=int)


arr

[50]: array([9, 5, 7, 0])

This constructor has created an object arr which is an instance of the class [Link]. This object
has some attributes that charactarize it:
[51]: print([Link])
print([Link])

(4,)
4
It has also methods that modifie it and returns information about it:
[52]: print([Link]())
print([Link]())

13
5.25
0

[53]: [Link]()
arr

[53]: array([0, 5, 7, 9])

Refer to the documentation to see all the available attributes and methods.

Creating a class Let’s start with a simple example:


[59]: class Rectangle():
"""
length: rectangle length
width: rectangle width
"""
# Constructor
def __init__(self, length, width):
[Link] = length
[Link] = width

def __str__(self):
return("rectangle of length {}cm and width {}cm".format([Link],␣
↪[Link]))

# Methods
def get_area(self):
return [Link] * [Link]

def get_perimeter(self):
return(2*([Link] + [Link]))

[58]: #help(Rectangle)

[60]: rectangle = Rectangle(length=10, width=5)


print(rectangle)

rectangle of length 10cm and width 5cm

[61]: print(rectangle.get_area(),rectangle.get_perimeter())

50 30

Inheritance and overriding Inheritance is a mechanism that allows you to create a hierarchy
of classes that share a set of properties and methods by deriving a class from a parent class.
In the following, we consider Person class which will be the parent class:

14
[62]: class Person():
"""
name: Person's name
"""
def __init__(self, name):
[Link] = name
[Link] = None

def __str__(self):
return("Person: {}".format([Link]))

def set_age(self, age):


[Link] = age

def get_age(self):
return([Link])

[63]: person = Person(name="Robert")


print(person)

Person: Robert

[64]: person.set_age(42)
person.get_age()

[64]: 42

We define now a child class Student which inherits from Person class with some extra properties:
[66]: class Student(Person):
"""
name: Person's name
age: Person's age
"""
def __init__(self, name, field):
[Link] = field
[Link] = None
super().__init__(name)

def __str__(self):
return("Student {}, field {}".format([Link], [Link]))

def set_year(self, year):


[Link] = year

def get_year(self):
return([Link])

15
This child class Student inherits the attributes name and age and the methods set_age() and
get_age() from the parent class Person:

[67]: student = Student(name="Maëlle", field="Computer science")


print(student)

Student Maëlle, field Computer science

[68]: student.set_age(22)
student.get_age()

[68]: 22

But it has two extra attributes field and year and two extra methods set_year() and
get_year():

[69]: student.set_year(4)
student.get_year()

[69]: 4

The method __str__ that it prints the name and the field overrides inheritance. The super()
function is used to refer to the parent class or superclass. It allows to call methods defined in the
superclass from the subclass, enabling you to extend and customize the functionality inherited from
the parent class.

1.2 Exercices
1.2.1 Exercice 1
1. Define a function fibonnacci(n) that returns the list of 𝑛 ≥ 0 first elements of fibonnacci
sequence defined as:
⎧𝑢0 = 0,
{
⎨𝑢1 = 1,
{𝑢
⎩ 𝑛+2 = 𝑢𝑛+1 + 𝑢𝑛 .
[ ]: # Answer

2. Define a function pascal(n) that returns a list that contains elements of the 𝑛-th line of the
Pascal’s triangle.
[ ]: # Answer

3. Let (𝑢𝑛 )𝑛∈ℕ and (𝑣𝑛 )𝑛∈ℕ be two numerical sequences defined as 𝑢0 = 1, 𝑣0 = 1, and ∀𝑛 ≥ 0:

𝑢𝑛+1 = 𝑢𝑛 + 𝑣𝑛 , 𝑣𝑛+1 = 2𝑢𝑛 − 𝑣𝑛 ,

Compute 𝑢100 and 𝑣100

[ ]: # Answer

16
4. Let 𝑛0 , 𝐾 ≥ 1 be two integers. Let 𝑣 = (𝑣𝑘 )𝑘∈ℕ be the sequence defined by 𝑣0 = 𝑛0 and

3𝑣 + 1 if 𝑣𝑘 is odd,
𝑣𝑘+1 = { 𝑣𝑘 𝑘
2 if 𝑣𝑘 is even,
Define a function vk(n0, K) that returns 𝐾 first elements of the sequence 𝑣.
[ ]: # Answer

For 𝐾 = 1000 and for every 𝑛0 ∈ {10, 100, 1000, 10000} print the last five values.

[ ]: # Answer

5. Define a function wallis(n) that computes an approximation of 𝜋 using the Wallis product.
[ ]: # Answer

1.2.2 Exercice 2
Consider the following list of dictionaries of persons with their weight (kg) and height (m):

[ ]: Persons = [{"Name": "Robert", "Weight": 95 , "Height": 1.81},


{"Name": "Alice", "Weight": 48 , "Height": 1.69},
{"Name": "Maëlle", "Weight": 61 , "Height": 1.57},
{"Name": "Maxime", "Weight": 140, "Height": 1.98}]

We recall, that the Body Mass Index (BMI) given the Weight (kg) and Heigth (m) is computed as
follows:
𝑊 𝑒𝑖𝑔ℎ𝑡
𝐵𝑀 𝐼 =
𝐻𝑒𝑖𝑔ℎ𝑡2
1. Define a function body_mass_index(weight,height) that returns a tuple (bmi,
interpretation) that contains the BMI and its interpretation (i.e., Underweigth, Nomal, or
Obese). Please refer to [Link] to interpret the BMI.

[ ]: # Answer

2. Write a script that adds the fields Bmi and Indication which are the BMI and its interpre-
tation to each dictionnary defined above.
[ ]: # Answer

1.2.3 Exercice 3
1. Plot in the same graph the functions 𝑠𝑖𝑛(𝑘𝑥) and 𝑐𝑜𝑠(𝑘𝑥) for 𝑘 = 1, 2, 3 and 𝑥 ∈ [0, 2𝜋]. Add
a title, set x and y axis to x and y respectively, add a legend in bottom left corner position
and set the x axis labels to {0, 𝜋2 , 𝜋, 3𝜋
1 , 2𝜋}.

[ ]: # Answer

17
Plot the Lemniscate of Bernoulli parametrized by:
√ √
2𝑐𝑜𝑠(𝑡) 2𝑐𝑜𝑠(𝑡)𝑠𝑖𝑛(𝑡)
𝑥= 2
, 𝑦= , 𝑡 ∈ [0, 2𝜋].
𝑠𝑖𝑛 (𝑡) + 1 𝑠𝑖𝑛2 (𝑡) + 1

[ ]: # Answer

1.2.4 Exercice 4
1. Create a class Circle with the attribute 𝑅 which represents the radius. Define a constructor
that constructs the class given the Radius and a method that prints “This is a circle with
radius R.”. Instanciate an object of the class Circle with 𝑅 = 3 and print the object.
[ ]: # Answer

2. Define three methods get_diameter(), get_perimeter() and get_area() that return the
diameter, the perimeter and the area of the circle.
[ ]: # Answer

3. Define a child class Sphere that inherits from the Circle class. Adapt the methods if neces-
sary. What can you say about the methods.
[ ]: # Answer

4. Define an extra method get_volume() that returns the volume of the sphere.

[ ]: # Answer

18

You might also like