Homepage Education

Introduction to the Python language

-- Numerical simulation in fluid mechanics --

Python basics

Introduction to scientific Python

-

simon.marie@lecnam.net

Running a Python script

Python is an interpreted language, so no compilation step is needed. There are 3 main ways to use Python:

  1. Write a script in a .py file and run it from the command line
  2. Use Python interactively with IPython or Spyder
  3. Use a Jupyter notebook (the approach used here)

To run a Python script, simply type the following command in a terminal:

 

$> python script.py

 

For this lab session, you can write a Python script with the editor of your choice (notepad++, emacs, vi, gedit...).

Importing modules

The first lines of a Python script import the modules needed for the computations, using the command import. For this lab session, the modules numpy, matplotlib et math are needed. The script will therefore start like this:

In [4]:
import numpy as np # contains useful functions for working with matricesimport matplotlib.pyplot as plt # contains useful functions for plotting%matplotlib inline
 

The lines above import the module numpy under the name np. All calls to functions of the module numpy are then prefixed with np.:

In [5]:
y=np.sin(np.pi) # compute sin(pi)print y
 
1.22464679915e-16
 

Working with vectors and matrices

The $\textit{numpy}$ module handles matrices in Python. To create and initialise a matrix, use the $\textit{zeros}$ function of $\textit{numpy}$. The function arange(n) of $\textit{numpy}$ creates a list of integers from $0$ to $n-1$.

In [7]:
nx=10ny=10A=np.zeros((nx,ny)) # nx*ny matrix of zerosB=np.arange(nx) # Vector of nx elements from 0 to 9print Aprint B
 
[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.] [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.] [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.] [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.] [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.] [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.] [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.] [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.] [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.] [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]][0 1 2 3 4 5 6 7 8 9]
 

Note that Python indices start at 0! You can select or modify part of a matrix by selecting its indices, as shown below:

In [10]:
print B[:] # All elements of the matrixprint B[0] # First row of the matrixprint B[-1] # Last row of the matrixprint B[-2] # Second-to-last row of the matrix...print B[0:5,] # Rows 1 to 5 and all columns.print B[0:-1] # Note: this only goes up to n-1print B[0:]  # Equivalent to B[:]# A[n1:n2,:] # selects n1 to n2-1, i.e. rows n1+1 to n2
 
[0 1 2 3 4 5 6 7 8 9]098[0 1 2 3 4][0 1 2 3 4 5 6 7 8][0 1 2 3 4 5 6 7 8 9]
 

To create vectors of evenly spaced numbers (e.g. for meshes), use the $\textit{arange(start,end,step)}$ function of $\textit{numpy}$:

In [11]:
A=np.arange(-2,2,0.5) # Vector of all numbers from -2 to 1.5 in steps of 0.5print A
 
[-2.  -1.5 -1.  -0.5  0.   0.5  1.   1.5]
 

To create a diagonal matrix, use the $\textit{eye(nx,ny)}$ function of $\textit{numpy}$:

In [12]:
B=np.eye(3,3) # 3*3 identity matrixprint B
 
[[ 1.  0.  0.] [ 0.  1.  0.] [ 0.  0.  1.]]
 

Python loops

Python syntax is based on indentation, so all lines of a block must start at the same position. The start and end of a loop (for, if, while...) are marked by a change of indentation. This Python-specific syntax removes the need for statements such as end for but it requires rigour! By convention, indentation is 4 spaces. A for loop is written as follows:

In [16]:
A=np.arange(10)for i in A:    print i,i**2,i**3
 
0 0 01 1 12 4 83 9 274 16 645 25 1256 36 2167 49 3438 64 5129 81 729
 

Do not forget the $:$ at the end of the first line of the loop.

 

Plotting

The module matplotlib provides plotting functions such as plot() et pcolormesh():

In [3]:
x=np.arange(-10,10,0.5)y=np.arange(-10,10,0.5)z=np.exp(-x**2/16)z2=np.einsum('i,j->ij',np.exp(-x**2/16),np.exp(-y**2/16))print z2.shapefig=plt.figure(1) # Create figure object 1plt.plot(x,z) # Plot y as a function of xplt.xlabel('You can label the axes $\epsilon$',fontsize=16.)plt.ylabel('Use symbols: $\sum_\infty \epsilon$',fontsize=16.)plt.title('Plot title',fontsize=16.)
 
(40, 40)
Out[3]:
<matplotlib.text.Text at 0x7f2c6c5daf50>