You are on page 1of 26

Introduction Python

Alexandre Gramfort : alexandre.gramfort@telecom-paristech.fr


Slim Essid : slim.essid@telecom-paristech.fr
adapt du travail de J.R. Johansson (robert@riken.jp) http://dml.riken.jp/~rob/
Installation
Linux
Sous Ubuntu Linux:
$ sudo apt-get install python ipython ipython-notebook
$ sudo apt-get install python-numpy python-scipy python-matplotlib python-sympy
$ sudo apt-get install spyder
MacOS X
Anaconda CE
Enthought Python Distribution. EPD commercial mais gratuit pour une utilisation acadmique.
Macports : http://www.macports.org
$ sudo port install py27-ipython +pyside+notebook+parallel+scientific
$ sudo port install py27-scipy py27-matplotlib py27-sympy
$ sudo port install py27-spyder
Pour choisir sa version de Python:
$ sudo port select python python27
$ sudo port select ipython ipython27
Fink : http://www.finkproject.org/
$ sudo fink install python27 ipython-py27 numpy-py27 matplotlib-py27 scipy-py27 sympy-py27
$ sudo fink install spyder-mac-py27
Windows
Python(x,y) (recommand)
Anaconda CE
Enthought Python Distribution. EPD commercial mais gratuit pour une utilisation acadmique.
Remarque
EPD et Anaconda CE sont aussi disponibles sous Linux
Lancer un programme Python
Un fichier python termine par ".py":
mon_programme.py
Toutes les lignes d'un fichier Python sont exccutes sauf les lignes qui commencent par # qui sont des commentaires.
Pour lancer le programme depuis une ligne de commande ou un terminal:
$ python mon_programme.py
Sous UNIX (Linux / Mac OS) il est courant d'ajouter le chemin vers l'interprteur python sur la premire ligne du fichier:
#!/usr/bin/env python
Cela permet de lancer un progamme directement:
$ mon_programme.py
Exemple:
In [1]: ls scripts/hello-world.py
In [2]: cat scripts/hello-world.py
scripts/hello-world.py*
In [2]: cat scripts/hello-world.py
In [3]: !./scripts/hello-world.py
Commencer une ligne par ! dans ipython permet de lancer une commande UNIX.
L'interprteur Python (mode intractif)
L'interprteur Python se lance avec la commande python. Pour sortir taper exit() ou Ctrl+D
IPython
IPython est un shell interactif beaucoup plus avanc.
#!/usr/bin/env python
print("Hello world!")
Hello world!
Il permet notamment de:
mmoriser les commandes lances prcdemment avec les flches (haut et bas).
auto-compltion avec Tab.
dition de code inline
accs simple la doc
debug
Spyder
Spyder est un IDE similaire MATLAB.
Les advantages de Spyder:
Bon diteur (couleurs, intgr avec le debugger).
Explorateur de variables, intgration de IPython
Documentation intgre.
IPython notebook
IPython notebook comme Mathematica ou Maple dans une page web.
Pour lancer ipython-notebook:
$ ipython notebook
depuis un dossier o seront stocks les notebooks (fichiers *.ipynb)
Les nombres
In [4]: 2 + 2 # commentaire
In [5]: a = 4
print a
print type(a)
Les noms de variable peuvent contenir a-z, A-Z, 0-9 et quelques caractres spciaux tels que _ mais commencent toujours par une
lettre.
Par convention les noms de variables sont en minuscule.
Quelques noms de variable ne sont pas autoriss car dj utiliss par le langage:
and, as, assert, break, class, continue, def, del, elif, else, except,
Out[4]: 4
4
<type 'int'>
exec, finally, for, from, global, if, import, in, is, lambda, not, or,
pass, print, raise, return, try, while, with, yield
In [6]: int a = 1; # in C
In [18]: c = 2.1 # nombre flottant
print type(c)
In [19]: a = 1.5 + 0.5j # nombre complexe
print a.real
print a.imag
print 1j
print a
print a + 1j
print 1j * 1j
print type(a)
In [20]: 3 < 4 # bool
In [21]: 3 < 2
In [22]: test = (3 > 4)
print test
In [23]: type(test)
In [24]: print 7 * 3. # int x float -> float
print type(7 * 3.)
In [25]: 2 ** 10 # exposant. attention pas ^
In [26]: 8 % 3 # reste de la division (modulo)
Attention !
In [27]: 3 / 2 # int x int -> int
In [28]: 3 / 2. # OK
File "<ipython-input-6-232418b2343a>", line 1
int a = 1; # in C
^
SyntaxError: invalid syntax
<type 'float'>
1.5
0.5
1j
(1.5+0.5j)
(1.5+1.5j)
(-1+0j)
<type 'complex'>
Out[20]: True
Out[21]: False
False
Out[23]: bool
21.0
<type 'float'>
Out[25]: 1024
Out[26]: 2
Out[27]: 1
In [28]: 3 / 2. # OK
In [29]: 3 // 2.0
In [30]: a = 2
3 / float(a) # OK
MAIS:
In [31]: cos(2)
La bibliothque standard et ses modules
Les fonctions Python sont organises par modules
Bibliothque standard Python (Python Standard Library) : collection de modules donnant accs des fonctionnalits de
bases : appels au systme d'exploitation, gestion des fichiers, gestion des chanes de caractres, interface rseau, etc.
Rfrences
The Python Language Reference: http://docs.python.org/2/reference/index.html
The Python Standard Library: http://docs.python.org/2/library/
Utilisation des modules
Un module doit tre import avant de pouvoir tre utilis, exemple :
In [32]: import math
Le module math peut maintenant tre utilis dans la suite du programme :
In [33]: import math
x = math.cos(2 * math.pi)
print x
Ou bien en important que les fonctions dont on a besoin:
In [34]: from math import cos, pi
x = cos(2 * pi)
print x
In [35]: from math import *
tanh(1)
In [36]: import math as m
print m.cos(1.)
Out[28]: 1.5
Out[29]: 1.0
Out[30]: 1.5
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-31-43abd96808db> in <module>()
----> 1 cos(2)
NameError: name 'cos' is not defined
1.0
1.0
Out[35]: 0.7615941559557649
Connaitre le contenu d'un module
Une fois un module import on peut lister les symboles disponibles avec la fonction dir:
In [37]: import math
print dir(math)
Pour accder l'aide : help
In [38]: help(math.log)
Dans Spyder ou IPython, on peut faire:
In [39]: math.log?
In [40]: math.log(10)
In [41]: math.log(10, 2)
In [42]: math.ceil(2.5)
help peut tre aussi utilise sur des modules :
In [43]: help(math)
0.540302305868
['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh',
'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf',
'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma',
'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi',
'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
Help on built-in function log in module math:
log(...)
log(x[, base])

Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
Out[40]: 2.302585092994046
Out[41]: 3.3219280948873626
Out[42]: 3.0
Help on module math:
NAME
math
FILE
/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/lib-dynload/math.so
MODULE DOCS
http://docs.python.org/library/math
DESCRIPTION
This module is always available. It provides access to the
mathematical functions defined by the C standard.
FUNCTIONS
acos(...)
acos(x)

Return the arc cosine (measured in radians) of x.

acosh(...)
acosh(x)

Return the hyperbolic arc cosine (measured in radians) of x.

asin(...)
asin(x)

Return the arc sine (measured in radians) of x.

asinh(...)
asinh(x)

Return the hyperbolic arc sine (measured in radians) of x.

atan(...)
atan(x)

Return the arc tangent (measured in radians) of x.

atan2(...)
atan2(y, x)

Return the arc tangent (measured in radians) of y/x.
Unlike atan(y/x), the signs of both x and y are considered.

atanh(...)
atanh(x)

Return the hyperbolic arc tangent (measured in radians) of x.

ceil(...)
ceil(x)

Return the ceiling of x as a float.
This is the smallest integral value >= x.

copysign(...)
copysign(x, y)

Return x with the sign of y.

cos(...)
cos(x)

Return the cosine of x (measured in radians).

cosh(...)
cosh(x)

Return the hyperbolic cosine of x.

degrees(...)
degrees(x)

Convert angle x from radians to degrees.

erf(...)
erf(x)

Error function at x.

erfc(...)
erfc(x)

Complementary error function at x.

exp(...)
exp(x)

Return e raised to the power of x.

expm1(...)
expm1(x)

Return exp(x)-1.
This function avoids the loss of precision involved in the direct evaluation of
exp(x)-1 for small x.

fabs(...)
fabs(x)

Return the absolute value of the float x.

factorial(...)
factorial(x) -> Integral

Find x!. Raise a ValueError if x is negative or non-integral.

floor(...)
floor(x)

Return the floor of x as a float.
This is the largest integral value <= x.

fmod(...)
fmod(x, y)

Return fmod(x, y), according to platform C. x % y may differ.

frexp(...)
frexp(x)

Return the mantissa and exponent of x, as pair (m, e).
m is a float and e is an int, such that x = m * 2.**e.
If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.

fsum(...)
fsum(iterable)

Return an accurate floating point sum of values in the iterable.
Assumes IEEE-754 floating point arithmetic.

gamma(...)
gamma(x)

Gamma function at x.

hypot(...)
hypot(x, y)

Return the Euclidean distance, sqrt(x*x + y*y).

isinf(...)
isinf(x) -> bool

Check if float x is infinite (positive or negative).

isnan(...)
isnan(x) -> bool

Check if float x is not a number (NaN).

ldexp(...)
ldexp(x, i)

Return x * (2**i).

lgamma(...)
lgamma(x)

Natural logarithm of absolute value of Gamma function at x.

Modules utiles de bibliothque standard: os, sys, math, shutil, re, etc.
Pour une liste complte, voir: http://docs.python.org/2/library/
log(...)
log(x[, base])

Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.

log10(...)
log10(x)

Return the base 10 logarithm of x.

log1p(...)
log1p(x)

Return the natural logarithm of 1+x (base e).
The result is computed in a way which is accurate for x near zero.

modf(...)
modf(x)

Return the fractional and integer parts of x. Both results carry the sign
of x and are floats.

pow(...)
pow(x, y)

Return x**y (x to the power of y).

radians(...)
radians(x)

Convert angle x from degrees to radians.

sin(...)
sin(x)

Return the sine of x (measured in radians).

sinh(...)
sinh(x)

Return the hyperbolic sine of x.

sqrt(...)
sqrt(x)

Return the square root of x.

tan(...)
tan(x)

Return the tangent of x (measured in radians).

tanh(...)
tanh(x)

Return the hyperbolic tangent of x.

trunc(...)
trunc(x:Real) -> Integral

Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.
DATA
e = 2.718281828459045
pi = 3.141592653589793
EXERCICE : Ecrire un code qui calcule la premire puissance de 2 suprieure un nombre n
In [44]: n = 12345
int(2 ** math.ceil(math.log(n, 2)))
Fractions
In [45]: import fractions
a = fractions.Fraction(2, 3)
b = fractions.Fraction(1, 2)
print a + b
On peut utiliser isinstance pour tester les types des variables :
In [46]: print type(a)
print isinstance(a, fractions.Fraction)
In [47]: a = fractions.Fraction(1, 1)
print isinstance(a, int)
Type casting (conversion de type)
In [48]: x = 1.5
print x, type(x)
In [49]: x = int(x)
print x, type(x)
In [50]: z = complex(x)
print z, type(z)
In [51]: x = float(z)
print x, type(x)
Operateurs et comparaisons
In [52]: 1 + 2, 1 - 2, 1 * 2, 1 / 2 # + - / * sur des entiers
In [53]: 1.0 + 2.0, 1.0 - 2.0, 1.0 * 2.0, 1.0 / 2.0 # + - / * sur des flottants
Out[44]: 16384
7/6
<class 'fractions.Fraction'>
True
False
1.5 <type 'float'>
1 <type 'int'>
(1+0j) <type 'complex'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-51-b47ba47d3a3d> in <module>()
----> 1 x = float(z)
2 print x, type(x)
TypeError: can't convert complex to float
Out[52]: (3, -1, 2, 0)
In [53]: 1.0 + 2.0, 1.0 - 2.0, 1.0 * 2.0, 1.0 / 2.0 # + - / * sur des flottants
In [54]: # Division entire
3.0 // 2.0
In [55]: # Attention ** et pas ^
2 ** 2
Oprations boolennes en anglais and, not, or.
In [56]: True and False
In [57]: not False
In [58]: True or False
Comparisons >, <, >= (plus grand ou gal), <= (infrieur ou gal), == equalit, is identique.
In [59]: 2 > 1, 2 < 1
In [60]: 2 > 2, 2 < 2
In [61]: 2 >= 2, 2 <= 2
In [62]: 2 != 3
In [63]: log(2), log(3)
In [64]: # galit
[1,2] == [1,2]
In [65]: # objets identiques?
l1 = l2 = [1,2]
# ou bien
l1 = [1,2]
l2 = l1
print l1 is l2
# ou bien
Out[53]: (3.0, -1.0, 2.0, 0.5)
Out[54]: 1.0
Out[55]: 4
Out[56]: False
Out[57]: True
Out[58]: True
Out[59]: (True, False)
Out[60]: (False, False)
Out[61]: (True, True)
Out[62]: True
Out[63]: (0.6931471805599453, 1.0986122886681098)
Out[64]: True
l1 = [1,2]
l2 = [1,2]
print l1 is l2
Conteneurs: Chanes de caractres, listes et dictionnaires
Chaines de caractres (Strings)
In [66]: s = 'Hello world!'
# ou avec " "
s = "Hello world!"
print s
print type(s)
Attention: les indices commencent 0!
On peut extraire une sous-chaine avec la syntaxe [start:stop], qui extrait les caractres entre start et stop (exclu) :
In [67]: s[0] # premier lment
In [68]: s[-1] # dernier lment
In [69]: s[0:5]
In [70]: start, stop = 1, 5
print len(s[start:stop])
print stop - start
In [71]: print start
print stop
Attention car :
In [72]: len("")
Mais:
In [73]: len(u"") # chaine de caractres unicode
On peut omettre start ou stop. Dans ce cas les valeurs par dfaut sont respectivement 0 et la fin de la chaine.
In [74]: s[:5] # 5 premires valeurs
In [75]: s[6:] # de l'entre d'indice 6 la fin
True
False
Hello world!
<type 'str'>
Out[67]: 'H'
Out[68]: '!'
Out[69]: 'Hello'
4
4
1
5
Out[72]: 2
Out[73]: 1
Out[74]: 'Hello'
In [76]: s[-6:] # les 6 derniers
Il est aussi possible de dfinir le step (pas d'avancement) avec la syntaxe [start:stop:step] (la valeur par dfaut de step est
1):
In [77]: s[::1]
In [78]: s[::2]
Cette technique est appele slicing. Pour en savoir plus: http://docs.python.org/release/2.7.3/library/functions.html?
highlight=slice#slice et http://docs.python.org/2/library/string.html
EXERCICE : A partir des lettres de l'alphabet, gnrer par une operation de slicing la chane de charactre cfilorux
In [79]: import string
alphabet = string.ascii_lowercase
print alphabet
print alphabet[2::3]
Mise en forme de chanes de caractres
In [80]: print "str1", "str2", "str3" # print ajoute des espaces entre les chanes
In [81]: print "str1", 1.0, False, -1j # print convertit toutes les variables en chanes
In [82]: print "str1" + "str2" + "str3" # pour concatener +
In [83]: print "str1" * 3
In [84]: print "val = %f" % 1.0 # comme en C (cf. printf)
In [85]: # Plus avanc
s = "val1 = %.2f, val2 = %d" % (3.1415, 1.5)
print s
Listes
Les listes sont trs similaires aux chanes de caractres sauf que les lments peuvent tre de n'importe quel type.
La syntaxe pour crer des listes est [...]:
In [86]: l = [1, 2, 3, 4]
print type(l)
print l
Exemples de slicing:
Out[75]: 'world!'
Out[76]: 'world!'
Out[77]: 'Hello world!'
Out[78]: 'Hlowrd'
abcdefghijklmnopqrstuvwxyz
cfilorux
str1 str2 str3
str1 1.0 False -1j
str1str2str3
str1str1str1
val = 1.000000
val1 = 3.14, val2 = 1
<type 'list'>
[1, 2, 3, 4]
In [87]: print l[1:3]
print l[::2]
Attention: On commence indexer 0!
In [88]: l[0]
On peut mlanger les types:
In [89]: l = [1, 'a', 1.0, 1-1j]
print l
On peut faire des listes de listes (par exemple pour dcrire un arbre...)
In [90]: list_of_list = [1, [2, [3, [4, [5]]]]]
list_of_list
In [91]: arbre = [1, [2, 3]]
print arbre
La fonction range pour gnrer une liste d'entiers:
In [92]: start, stop, step = 10, 30, 2
range(start, stop, step)
In [93]: range(-10, 10)
In [94]: # convertir une chaine de caractre en liste
s2 = list(s)
s2
In [95]: # tri
s2.sort()
print s2
[2, 3]
[1, 3]
Out[88]: 1
[1, 'a', 1.0, (1-1j)]
Out[90]: [1, [2, [3, [4, [5]]]]]
[1, [2, 3]]
Out[92]: [10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
Out[93]: [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Out[94]: ['v',
'a',
'l',
'1',
' ',
'=',
' ',
'3',
'.',
'1',
'4',
',',
' ',
'v',
'a',
'l',
'2',
' ',
'=',
' ',
'1']
print s2[::-1]
Attention s2.sort() ne renvoie rien c'est--dire None
In [96]: out = s2.sort()
print out
Pour renvoyer une nouvelle liste trie:
In [97]: out = sorted(s2)
print out
Ajout, insertion, modifier, et enlever des lments d'une liste:
In [98]: # cration d'une liste vide
l = []
# ajout d'lments avec `append`
m = l.append("A")
l.append("d")
l.append("d")
print m
print l
In [99]: l.count?
On peut modifier une liste par assignation:
In [100]: l[1] = "p"
l[2] = "p"
print l
In [101]: l[1:3] = ["d", "d"]
print l
Insertion un index donn avec insert
In [102]: l.insert(0, "i")
l.insert(1, "n")
l.insert(2, "s")
l.insert(3, "e")
l.insert(4, "r")
l.insert(5, "t")
print l
Suppression d'un lment avec 'remove'
In [103]: l.remove("A")
print l
In [104]: ll = [1, 2, 3, 2]
print ll
[' ', ' ', ' ', ' ', ' ', ',', '.', '1', '1', '1', '2', '3', '4', '=', '=', 'a', 'a',
'l', 'l', 'v', 'v']
['v', 'v', 'l', 'l', 'a', 'a', '=', '=', '4', '3', '2', '1', '1', '1', '.', ',', ' ', '
', ' ', ' ', ' ']
None
[' ', ' ', ' ', ' ', ' ', ',', '.', '1', '1', '1', '2', '3', '4', '=', '=', 'a', 'a',
'l', 'l', 'v', 'v']
None
['A', 'd', 'd']
['A', 'p', 'p']
['A', 'd', 'd']
['i', 'n', 's', 'e', 'r', 't', 'A', 'd', 'd']
['i', 'n', 's', 'e', 'r', 't', 'd', 'd']
ll.remove(2)
print ll
In [105]: 2 in ll
ll.index(2)
Suppression d'un lment une position donne avec del:
In [106]: del l[7]
del l[6]
print l
help(list) pour en savoir plus.
Tuples
Les tuples (n-uplets) ressemblent aux listes mais ils sont immuables : ils ne peuvent pas tre modifis une fois crs.
On les cre avec la syntaxe (..., ..., ...) ou simplement ..., ...:
In [107]: point = (10, 20)
print point, type(point)
Un tuple peut tre dpil par assignation une liste de variables spares par des virgules :
In [108]: x, y = point
print "x =", x
print "y =", y
On ne peut pas faire :
In [109]: point[0] = 20
Dictionnaires
Ils servent stocker des donnes de la forme cl-valeur.
La syntaxe pour les dictionnaires est {key1 : value1, ...}:
In [110]: params = {"parameter1" : 1.0,
"parameter2" : 2.0,
"parameter3" : 3.0}
# ou bien
params = dict(parameter1=1.0, parameter2=2.0, parameter3=3.0)
print type(params)
print params
In [111]: print "parameter1 =", params["parameter1"]
[1, 2, 3, 2]
[1, 3, 2]
Out[105]: 2
['i', 'n', 's', 'e', 'r', 't']
(10, 20) <type 'tuple'>
x = 10
y = 20
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-109-ac1c641a5dca> in <module>()
----> 1 point[0] = 20
TypeError: 'tuple' object does not support item assignment
<type 'dict'>
{'parameter1': 1.0, 'parameter3': 3.0, 'parameter2': 2.0}
In [111]: print "parameter1 =", params["parameter1"]
print "parameter2 =", params["parameter2"]
print "parameter3 =", params["parameter3"]
In [112]: params["parameter1"] = "A"
params["parameter2"] = "B"
# ajout d'une entre
params["parameter4"] = "D"
print "parameter1 =", params["parameter1"]
print "parameter2 =", params["parameter2"]
print "parameter3 =", params["parameter3"]
print "parameter4 =", params["parameter4"]
Suppression d'une cl:
In [113]: del params["parameter4"]
print params
Test de prsence d'une cl
In [114]: "parameter1" in params
In [115]: "parameter6" in params
In [116]: params["parameter6"]
Conditions, branchements et boucles
Branchements: if, elif, else
In [117]: statement1 = False
statement2 = False
if statement1:
print "statement1 is True"
elif statement2:
print "statement2 is True"
else:
print "statement1 and statement2 are False"
En Python l'indentation est obligatoire car elle influence l'excution du code
Examples:
In [118]: statement1 = statement2 = True
parameter1 = 1.0
parameter2 = 2.0
parameter3 = 3.0
parameter1 = A
parameter2 = B
parameter3 = 3.0
parameter4 = D
{'parameter1': 'A', 'parameter3': 3.0, 'parameter2': 'B'}
Out[114]: True
Out[115]: False
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-116-9d26f4da51fe> in <module>()
----> 1 params["parameter6"]
KeyError: 'parameter6'
statement1 and statement2 are False
In [118]: statement1 = statement2 = True
if statement1:
if statement2:
print "both statement1 and statement2 are True"
In [119]: # Mauvaise indentation!
if statement1:
if statement2:
print "both statement1 and statement2 are True"
In [120]: statement1 = True
if statement1:
print "printed if statement1 is True"

print "still inside the if block"
In [121]: statement1 = False
if statement1:
print "printed if statement1 is True"

print "still inside the if block"
Boucles
Boucles for:
In [122]: for x in [1, 2, 3]:
print x
La boucle for itre sur les lments de la list fournie. Par exemple:
In [123]: for x in range(4): # par dfault range commence 0
print x
Attention range(4) n'inclut pas 4 !
In [124]: for x in range(-3,3):
print x
In [125]: for word in ["calcul", "scientifique", "en", "python"]:
print word
both statement1 and statement2 are True
IndentationError: expected an indented block
printed if statement1 is True
still inside the if block
still inside the if block
1
2
3
0
1
2
3
-3
-2
-1
0
1
2
calcul
scientifique
en
In [126]: for c in "calcul":
print c
Pour itrer sur un dictionnaire::
In [127]: for key, value in params.iteritems():
print key, " = ", value
In [128]: for x in params:
print x
Parfois il est utile d'accder la valeur et l'index de l'lment. Il faut alors utiliser enumerate:
In [129]: for idx, x in enumerate(range(-3,3)):
print idx, x
EXERCICE : Compter le nombre d'occurences de chaque charactre dans la chane de caractres "HelLo
WorLd!!"
In [130]: s = "HelLo WorLd!!"
s = s.lower()
d = {} # ou bien d = dict()
for c in s:
if c in d:
d[c] += 1 # quivalent d[c] = d[c] + 1
else:
d[c] = 1
print d
Comprhension de liste: cration de liste avec for:
In [131]: l1 = [x**2 for x in range(0,5)]
print l1
# est la version courte de :
ll = list()
for x in range(0, 5):
ll.append(x**2)
print ll
# pour les gens qui font du caml
python
c
a
l
c
u
l
parameter1 = A
parameter3 = 3.0
parameter2 = B
parameter1
parameter3
parameter2
0 -3
1 -2
2 -1
3 0
4 1
5 2
{'!': 2, ' ': 1, 'e': 1, 'd': 1, 'h': 1, 'l': 3, 'o': 2, 'r': 1, 'w': 1}
print map(lambda x: x**2, range(5))
Boucles while:
In [132]: i = 0
while i < 5:
print i
i = i + 1

print "OK"
EXERCICE :
Calculer une approximation de par la formule de Wallis
In [133]: import numpy as np
def wallis(n):
out = 2.
for i in range(1,n+1):
out *= 4*i**2 / (4*i**2-1.)
return out
print "%.20f" % wallis(10000)
def wallis_numpy(n):
tmp = 4. * (np.arange(1, n+1, dtype=float) ** 2)
return 2. * np.prod(tmp / (tmp - 1.))
print "%.20f" % wallis_numpy(10000)
# calcul de la vitesse d'excution avec la commande %timeit de IPython
n = 10000
%timeit wallis(n)
%timeit wallis_numpy(n)
# ou la main avec le module time de la librairie standard:
import time
t0 = time.time()
wallis(n)
print time.time() - t0
Fonctions
Une fonction en Python est dfinie avec le mot cl def, suivi par le nom de la fonction, la signature entre parenthses (), et un :.
Exemples:
In [134]: def func0():
[0, 1, 4, 9, 16]
[0, 1, 4, 9, 16]
[0, 1, 4, 9, 16]
0
1
2
3
4
OK
3.14151411868195662436
3.14151411868195662436
100 loops, best of 3: 3.91 ms per loop
10000 loops, best of 3: 143 us per loop
0.0048451423645
In [134]: def func0():
print "test"
In [135]: func0()
Ajout d'une documentation (docstring):
In [136]: def func1(s):
"""
Affichage d'une chaine et de sa longueur
"""
print s, "est de longueur", len(s)
In [137]: help(func1)
In [138]: print func1("test")
print func1([1, 2, 3])
Retourner une valeur avec return:
In [139]: def square(x):
"""
Returne le carr de x.
"""
return x ** 2
In [140]: print square(4)
Retourner plusieurs valeurs:
In [141]: def powers(x):
"""
Retourne les premires puissances de x.
"""
return x ** 2, x ** 3, x ** 4
In [142]: print powers(3)
print type(powers(3))
out = powers(3)
print len(out)
print out[1]
In [143]: x2, x3, x4 = powers(3)
print x3
Arguments par dfault
Il est possible de fournir des valeurs par dfault aux paramtres:
In [144]: def myfunc(x, p=2, debug=False):
test
Help on function func1 in module __main__:
func1(s)
Affichage d'une chaine et de sa longueur
test est de longueur 4
None
[1, 2, 3] est de longueur 3
None
16
(9, 27, 81)
<type 'tuple'>
3
27
27
if debug:
print "evalue myfunc avec x =", x, "et l'exposant p =", p
return x**p
Le paramtre debug peut tre omis:
In [145]: myfunc(5)
In [146]: myfunc(5, 3)
In [147]: myfunc(5, debug=True)
On peut expliciter les noms de variables et alors l'ordre n'importe plus:
In [148]: myfunc(p=3, debug=True, x=7)
In [149]: x = 1
def func2():
yyy = 1
def func1(ll):
ll += ll
print x
print yyy
a = [1, 2]
func1(a)
print a
Exercice: implmenter quicksort
La page wikipedia dcrivant lalgorithme de tri quicksort donne le pseudo-code suivant:
function quicksort('array')
if length('array') <= 1
return 'array'
select and remove a pivot value 'pivot' from 'array'
create empty lists 'less' and 'greater'
for each 'x' in 'array'
if 'x' <= 'pivot' then append 'x' to 'less'
else append 'x' to 'greater'
Out[145]: 25
Out[146]: 125
evalue myfunc avec x = 5 et l'exposant p = 2
Out[147]: 25
evalue myfunc avec x = 7 et l'exposant p = 3
Out[148]: 343
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-149-8621dd371f82> in <module>()
10
11 a = [1, 2]
---> 12 func1(a)
13 print a
<ipython-input-149-8621dd371f82> in func1(ll)
7 ll += ll
8 print x
----> 9 print yyy
10
11 a = [1, 2]
NameError: global name 'yyy' is not defined
1
return concatenate(quicksort('less'), 'pivot', quicksort('greater'))
Transformer ce pseudo-code en code valide Python.
Des indices:
la longueur dune liste est donne par len(l)
deux listes peuvent tre concatnes avec l1 + l2
l.pop() retire le dernier lment dune liste
Attention: une liste est mutable...
Il vous suffit de complter cette bauche:
In [150]: def quicksort(l):
# ...
return l
l = [3, 4, 1, 2, 5, 6]
print quicksort(l)
Classes
Les classes sont les lments centraux de la programmation oriente objet
Classe: structure qui sert reprsenter un objet et l'ensemble des oprations qui peuvent tres effectues sur ce dernier.
Dans Python une classe contient des attributs (variables) et des mthodes (fonctions). Elle est dfinie de manire analogue aux
fonctions mais en utilisant le mot cl class. La dfinition d'une classe contient gnralement un certain nombre de mthodes de
classe (des fonctions dans la classe).
Le premier argument d'un mthode doit tre self: argument obligatoire. Cet objet self est une auto-rfrence.
Certains noms de mthodes ont un sens particulier, par exemple :
__init__: nom de la mthode invoque la cration de l'objet
__str__ : mthode invoque lorsque une reprsentation de la classe sous forme de chane de caractres est demande,
par exemple quand la classe est passe print
voir http://docs.python.org/2/reference/datamodel.html#special-method-names pour les autres noms spciaux
Exemple
In [151]: class Point(object):
"""
Classe pour reprsenter un point dans le plan.
"""
def __init__(self, x, y):
"""
Creation d'un nouveau point en position x, y.
"""
self.x = x
self.y = y

def translate(self, dx, dy):
"""
Translate le point de dx and dy.
"""
self.x += dx
self.y += dy

def __str__(self):
return "Point: [%f, %f]" % (self.x, self.y)
Pour crer une nouvelle instance de la classe:
In [152]: p1 = Point(0, 0) # appel __init__
print p1.x
print p1.y
print p1 # appel la mthode __str__
[3, 4, 1, 2, 5, 6]
0
0
Point: [0.000000, 0.000000]
In [153]: p1.translate(1, 1)
print p1.translate
print p1
print type(p1)
Pour invoquer une mthode de la classe sur une instance p de celle-ci:
In [154]: p2 = Point(1, 1)
p1.translate(0.25, 1.5)
print p1
print p2
Remarques
L'appel d'une mthode de classe peut modifier l'tat d'une instance particulire
Cela n'affecte ni les autres instances ni les variables globales
Exceptions
Dans Python les erreurs sont gres travers des "Exceptions"
Une erreur provoque une Exception qui interrompt l'excution normale du programme
L'excution peut ventuellement reprendre l'intrieur d'un bloc de code try - except
Une utilisation typique: arrter l'excution d'une fonction en cas d'erreur:
def my_function(arguments):
if not verify(arguments):
raise Expection("Invalid arguments")
# et on continue
On utilise try et expect pour matriser les erreurs:
try:
# normal code goes here
except:
# code for error handling goes here
# this code is not executed unless the code
# above generated an error
Par exemple:
In [155]: try:
print "test_var"
# genere une erreur: la variable test n'est pas dfinie
print test_var
except:
print "Caught an expection"
Pour obtenir de l'information sur l'erreur: accder l'instance de la classe Exception concerne:
except Exception as e:
In [156]: try:
print "test"
# generate an error: the variable test is not defined
print test
<bound method Point.translate of <__main__.Point object at 0x575d3f0>>
Point: [1.000000, 1.000000]
<class '__main__.Point'>
Point: [1.250000, 2.500000]
Point: [1.000000, 1.000000]
test_var
Caught an expection
except Exception as e:
print "Caught an expection:", e
Manipuler les fichiers sur le disque
In [157]: import os
print os.path.join('~', 'work', 'src')
print os.path.expanduser(os.path.join('~', 'work', 'src'))
Quelques liens
http://www.python.org - Page Python officielle.
http://www.python.org/dev/peps/pep-0008 - Recommandations de style d'criture.
http://www.greenteapress.com/thinkpython/ - Un livre gratuit sur Python.
Python Essential Reference - Un bon livre de rfrence.
In []:
test
False
~/work/src
/Users/alex/work/src

You might also like