20160324_python
20160324_python
Contents
1 Introduction 2
1.1 Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2 basics 3
2.1 before starting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 print . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.3 if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.4 loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.5 list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.6 dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.7 tuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.8 Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.9 libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3 NO such basics 6
3.1 functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2 classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
5 drawing: matplotlib 9
6 Useful links 10
∗ Main author of this chapter: L. Fita, Laboratoire de Météorologie Dynamique (LMD). This work is licensed under Creative Commons
1
IPSL BootCamp: 2016/03/24. python 2
1 Introduction
Python was born on 1989 by ’Guido van Rossum’ and takes its name from the ’Monthy Python Flying Circus’1
It is a high level interpreted language, designed to be easy to be read and it is object-oriented.
There is a ‘new’ version of python (python 3.x) which is not compatible with the python.2.x. This course uses python
2.x. In a mid term is recommendable to migrate to python 3.x, nowadays (2016) might not be fully recommendable.
• High level language: Programmer does not need to worry to much about to deal with the CPU and memory.
It is done by the program which it has a high level of abstraction. That facilitates the coding and reading the
source, but penalize efficiency and speed
• Interpreted language: Code is not compiled. When on executes the source, it is read and executed
• Objects: Encapsulated data and methods in a single piece of code. Very versatile and flexible
• easy to be read: It is mandatory to indent the code
1.1 Object
In the old class programming languages like: C, Fortran, bash, ... variables might be algebraic data-sets (scalar,
vector, matrices) of 4 basic types: integer, float, boolean and character.
An object could be understood (in a very simple way) as a variable which has a more complex structure. It can
be a combination of variables, functions and data-sets. Thus it is not only a group of values, either a memory address
with a ‘dynamic’ behavior.
1 https://en.wikipedia.org/wiki/Monty_Python
IPSL BootCamp: 2016/03/24. python 3
2 basics
2.1 before starting
Some very basic zero stuff:
• #: comment character
• >>>: Terminal string in an ‘interactive’ python session (after $ python)
• Mandatory to indent on if, loop (recommended 4 white spaces)
• \: Character of continuation of line
2.2 print
Some initial prints:
Hola
Range print:
[0, 1, 2, 3]
2.3 if
’conditionals’, a ’nice’ if
i = 3
if i == 2: ’:’ to mark end of ‘if’
print 'two' ’indent’ mandatory !!
elif i == 3: no-indent as it is part of the initial ‘if’
print 'three'
else:
print 'whatever' No end if instruction, just do not indent
three
IPSL BootCamp: 2016/03/24. python 4
2.4 loops
Again, indented ‘nice’ loops
0
1
2
3
1
3
5
7
9
2.5 list
‘List’ is a data structure of values sorted as they fill it. It can grow, and it can contain different types of data
['1', 2.0, 3, 2]
2.6 dictionary
Data-structure composed with pairs of values like in a dictionary with its ‘word’ and its ‘meaning’. Values are not
alphabetically sorted. It can contain different kind of data
>>> lmdcouloir = { }
’{ }’ definition of a variable as a dictionary
>>> lmdcouloir['218'] = ['Shan', 'Lluis']
providing values for key ’218’ as a list
>>> lmdcouloir['313'] = 'seminar room'
providing values for key ’313’ as a string
>>> print lmdcouloir
printing content of the dictionary
{'313': 'seminar room', '218': ['Shan',
'Lluis']}
print content for the ’313’ value
>>> print lmdcouloir['313']
seminar room
Some methods of a dictionary:
>>> lmdcouloir.keys() listing all keys of the dictionary
['313', '218']
>>> lmdcouloir.has_key('315') search for the existence of a ‘key’
False
2.7 tuple
Data-structure with values. It can not grow. Data access is more faster. It can mix data types
>>> tuplevalues = () ‘( )’ definition of variable as tuple
>>> tuplevalues = (1, 2, 3, 89) assigning values to tuple
>>> print tuplevalues printing values
(1, 2, 3, 89)
2.8 Miscellaneous
Some general hints
• >>> print dir([obj]): list of the methods of [obj]
• >>> print [obj].__doc__: provides documentation of object [obj]
• >>> quit(): exiting python
• """: for documentation in a class/function
• ’Header’ beginning of scripts, where one can import a huge number of different libraries/modules/packages
2.9 libraries
python can be run with complementary powerful libraries. They cover a wide range of functinoalities and capabilities.
A very short and the most valuable ones is here given:
• numpy, scipy: the scientific numerical libraries
• os, subProcess: for system calls
• matplotlib: for plotting (similar to ’matplot’)
• datetime: for date/time variables
• optparse: parsing for arguments options when calling script
IPSL BootCamp: 2016/03/24. python 6
3 NO such basics
There are two main ways to generate self content actions: functions, classes
3.1 functions
The general structure of a function is this:
def FunctionName([Arg1], [Arg2], ...): ‘def’ marks definition of function ‘:’ end of definition
""" Description of the function ””” to start documentation of the function
""" ””” to end documentation of the function
fname = 'fibonacci'
When we call:
IPSL BootCamp: 2016/03/24. python 7
3.2 classes
’classes’, are similar to functions, but much more complex and flexible (too much for an introductory course!)
IPSL BootCamp: 2016/03/24. python 8
– [ncobj] = NetCDFFile([filename], ’[access]’): open a file [filename] as object [ncobj] with [access]=’w’,
write; ’a’, append, ’r’, read
– [ncobj].variables: dictionary will all the variables of the file
– [ncobj].dimensions: dictionary will all the dimensions of the file
– [ncvarobj] = [ncobj].variables[’varnaname’]: object [ncvarobj] with variable ’varname’
– [ncvarobj].dimensions: dictionary will all the dimensions of the variable ’varname’
– [ncvarobj][:]: all the values of variable ’varname’ (shape automatically given)
– [ncvarobj].shape: shape of the variable ’varname’
– createVariable([varname], [kind], [dimensions], fill_value=[missValue]): creation of a vari-
able with a missing value of [missValue]
• Example with ‘reading_nc.py’
import numpy as np
from netCDF4 import Dataset as NetCDFFile Importing ‘netCDF4’ module to manage netCDF
ncobj.close()
When we execute
$ python reading_nc.py
variables: [u'longitude', u'latitude', u'RELIEF']
dimension of the topography: (1080, 2160)
max. height: 7833.0 m
IPSL BootCamp: 2016/03/24. python 9
5 drawing: matplotlib
For plotting there is a matplot like environment http://matplotlib.org/. Very flexible, robust and powerful.
Example with ’plotting_topo.py’
import numpy as np
from netCDF4 import Dataset as NetCDFFile
import matplotlib as mpl importing ‘matplotlib’
mpl.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap importing coastal line for mapping
filename = 'Relief.nc'
toponame = 'RELIEF'
ncobj = NetCDFFile(filename, 'r') opening for reading netCDF
plt.rc('text', usetex=True) using LATEX like format for strings in the plot
Which generates:
6 Useful links
• Python Source: https://www.python.org/
• Shan’s python course: http://www.xn--llusfb-5va.cat/python/ShanCourse/PythonCourse.html (almost
the same content as here)
• List of some useful modules: https://wiki.python.org/moin/UsefulModules
• Aymeric Spiga’s PLANETOPLOT plotting toolkit from LMD useful to plot http://www.lmd.jussieu.fr/
~aslmd/planetoplot
• L. Fita’s netCDF/plottiong toolkit from LMD for netCDF file managements is already available from LMDZ_WRF
subversion trunk repository: