Introduction Python I.

Introduction to notebooks

First you need Jupyter. If you have Jupyter, you can launch it in a Terminal with

jupyter notebook

This should open a web navigator (such as Firefox) in which you can work. In the Home tab, you find your files.

Notebooks are composed of cells, which either contains some Python code, or some text. These notebooks offer a great tool to run code interactively, and is a must for teaching and learning.

You can edit a cell by double-clicking on it, and you can evaluate it with Ctrl+Enter (We often use Maj+Enter to evaluate and go to the next cell). The buttons in the toolbar are quite clear. Have a look at them.

Do not forget to save you work on a regular basis (even though Jupyter saves your work regularly).

Exercice : Click on Help -> User Interface Tour

Exercice : Delete the next cell. (see Help -> Keyboard Shortcuts) :

----- Please delete me ------------

The top shortcuts are

Markdown cell

Markdown is a simple text format which allows some formatting. you can:

Fun fact: You can write in Markdown in the famous App WhatsApp.

Exercice: Transform this word from italics to boldfont (hind : double click on the previous cell).

Python Cell

The next cell is a Python cell. You can evaluate it with Maj+Enter.

You can have interactive help. For instance, if you wish to know what a Python function does (say abs), you can either type help(abs) or abs?, or abs and Maj+Tab or Maj+2xTab.

Exercice: What is the function str() ? What is the difference between 2 and str(2)?

Uploading libraries

In Python, we upload libraries with import. For instance, most notebooks start with

import numpy as np import matplotlib.pyplot as plt import pandas as pd

Here, in order to avoid writing plt and np everytime, one can use the shortcut

%pylab inline

It loads many useful mathematical functions (numpy) and plot functions (matplotlib).

2. Basics in Python

Structure of the code Python

A Python code is structured with indentation.

WARNING: In Python, indices start at ZERO.

WARNING: Never use the While loop (computers may and will crash)!

In the next code, range(N) is the list [0, 1, ..., N-1].

Exercice: The next cell has errors. Correct them (and read the error messages)

Variables

Types

Python has several types (see next cell).

In addition, we work with numpy, which has the type array (= matrix)

Basic calculus

Python can handle the usual operations +,-,/,*, and many more. Here are some traps.

Print

The print function allows to print strings, as well as many other types

The correct way to format strings is with {} and format, see here. In short :

Booleans

Booleans have values True or False. The if command takes a boolean. Here are some tricks.

Lists

Python codes must be simple and effective. Here are some best practices.

We access an element of a list (or an array) with brakets. [].

Remark: In Python,

Matrices

We now deal with vectors and matrices. Lists are not suitable for numerical computations (see the next example), and the correct type is array from numpy.

As for lists, we can access the elements with brakets. For a matrix, we need 2 indices!

Create an array

We now describe several ways to create an array.

Create from a list

Basic matrices

Python knows some reference matrices.

Matrix computations

Warning: the product with * is a the term by term product (Hadamard product). To multiply two matrices, we use dot or @.

Warning: 1 is not the identity matrix.

Python knows some "usual" functions such as determinant, trace, norm, inv, ... You can easily solve systems.

Exercice: What is exp(eye(3))? How to compute the exponent of eye(3) ? (remember, internet is your friend... have a look at expm from scipy...)

Graphics

We use matplotlib to plot graphics.

The basic function is plot(x,y) where $x$ et $y$ are lists/array of same size. In pratice, $x$ usually represents the interval $[a,b]$, so you can use the command linspace.

Here is a full example to plot $f$.

Remark: I personnaly use xx for the interval in which x lives. And similarly for all variables.

You can easily plot parametrized curves. For instance, to plot $$ c(t) = (\sin^3(t), \cos(t) - \cos^4(t)), $$ we can use the following code

Exercice: How to have a red curve? How to make a "scatter" plot?

Finally, we can plot the level lines of a function with contour. Here for instance, we plot the level lines of $$ f(x,y) = e^{-y^2} \sin(x-y) $$

Histograms

We can also easily create histograms.

Exercice: Consider the rolling of a dice. Prove that the mean is $\mu := \mathbb{E}[X] = 7/2$ and the variance is $\sigma^2 = \mathbb{E}[(X - 7/2)^2] = 35/12$.

The Central Limit theorem states that if we roll M dices and average the result to get $Y$, then $$\dfrac{(Y - \mu)}{\sigma/\sqrt{M}} \approx \mathcal{N}(0, 1).$$

Exercice: Check the central limit theorem. Take $M = 1000$, and consider $N = 10000$ realisations of the experiment

Magic commands

We end this notebook with useful tricks from Jupyter. You can time a cell with the magic command %%time. Compare the two following codes

You can check what is time-consuming in your code with the profiler. You can install one with

pip install line_profiler

See the following example. First, we load the profiler

If you want to use an external Python file and interface it with Jupyter, you can use %autoreload, etc., etc.

Last but not least

Python has an active community. If you have a question about anything ("how to... ?", "why... ?", "what happens if... ?"), you can always ask on the internet.

In most cases, your question already has an answer somewhere on a forum

UPDATE: Do not hesitate to ask ChatGPT (or Perplexity for an anonymous equivalent) for Python code. The produced code is excellent, and you learn a lot by reading and studying it (of course, you may have to correct some bugs...).