Anda di halaman 1dari 53

Python  Cours 1

Jean-Yves Thibon
Université Paris-Est Marne-la-Vallée

http://igm.univ-mlv.fr/∼ jyt
Python

 Langage objet pour


 prototypage rapide
 langage de ontrle de grandes appli ations
 s ripts, administration
 Extensible (C/C++/Fortran ou Java)
 Libre
 Mature (depuis 1991, ommunauté nombreuse)
 Syntaxe on ise, laire et ohérente

1
CPython

 Extrêmement portable : Unix, Windows, Ma OS,


Symbian
 Interprété/ ompilé (byte ode)
 Sûr (pas de pointeurs, gestion automatique de la
mémoire)
 Nombreuses bibliothèques (réseau, bases de données,
interfa es graphiques, son, vidéo ...)
 Extensible C/C++/Fortran

2
Jpython (ex Jython)

 Totalement intégré ave Java


 Compilation dire te en byte ode Java
 Importation dire te des lasses Java
 Héritage depuis les lasses Java
 Support des JavaBeans, des applettes, des servlettes
 Même langage mais diéren es a tuellement dans les
modules d'extension

3
Bref historique

 Première version en février 1991


 Version 2.0 en 2000
 Aujourd'hui : version 2.6.4
 Version 3.0 en dé embre 2008, (quelques
in ompatibilités ave les pré édentes, 3.1.1
a tuellement)
 Versions embarquées (téléphones portables : Nokia série
6, Palm ...)
 Sta kless Python (mi rothreads, pour fa iliter la
programmation on urrente)

4
Cara téristiques du langage

 Tout est un objet


 Modules, lasses, fon tions
 Ex eptions
 Typage dynamique, polymorphisme
 Sur harge des opérateurs
 Syntaxe laire et intuitive : mix C/Algol, indentation
pour délimiter les blo s (pseudo- ode exé utable)

5
Des types de données de haut niveau

 Nombres : entiers, entiers longs, réels ottants,


omplexes
 Chaînes de ara tères (immuables)
 Tuples, listes et di tionnaires ( onteneurs)
 D'autres types natifs réés par des extensions en C
(expressions régulières, des ripteurs de  hiers,
so kets...)
 Instan es de lasses dénies en Python

6
Exemples

Un peu de mauvaise foi pour ommen er ... Java :


publi lass Hello {
publi stati void main(String[℄ args) {
System.out.println("Hello, World!");
}
}
Python :
print "Hello, World!" # 3.0: print("Hello world")

7
Plus instru tif ...

#!/usr/bin/python
'''hello.py: le programme 'Hello world' bien onnu.

Usage: hello.py [-h℄ [--help℄ [nom_de_personne℄+


'''

import sys, getopt

def usage():
'Print usage do and exit.'
print __do __
sys.exit()
8
try:
optlist, arglist = getopt.getopt(
sys.argv[1:℄, 'h', ['help'℄)
ex ept:
usage()

for option in optlist:


if option[0℄ in ['-h', '--help'℄:
usage()
if arglist:
for arg in arglist:
print 'Hello %s!' % arg
else: print "Hello world!"

9
Qui utilise Python ?

 Google (15% de leur ode base !)


 EDF ( ode Aster)
 Yahoo (Yahoo !mail)
 Mi rosoft (E-Commer e)
 Red Hat (Glint, setup tools), Ubuntu
 SGMLTools 2.0, OpenO e2.0,Vim 5...
 Communauté s ientique (Sage ...)
 Et bien d'autres ...

10
The Zen of Python

Python 2.5.1 (r251:54863, Sep 24 2007, 07:28:16)?


[GCC 4.1.1℄ on linux2
Type "help", " opyright", " redits" or "li ense" for more information.
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.


Expli it is better than impli it.
Simple is better than omplex.
Complex is better than ompli ated.
Flat is better than nested.
Sparse is better than dense.
Readability ounts.

11
Spe ial ases aren't spe ial enough to break the rules.
Although pra ti ality beats purity.
Errors should never pass silently.
Unless expli itly silen ed.
In the fa e of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dut h.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespa es are one honking great idea -- let's do more of those!

12
Premiers pas

On lan e l'interpréteur en tapant python au prompt :


[jytliszt jyt℄$ python
Python 2.6.1 (r261:67515, De 25 2008, 16:25:51)
[GCC 3.4.1 (Mandrakelinux 10.1 3.4.1-4mdk)℄ on linux2
Type "help", " opyright", " redits" or "li ense" for more information.
>>> 2**100
1267650600228229401496703205376L
On peut aussi é rire des s ripts
[jytliszt jyt℄$ at a.py
#!/usr/bin/env python
print 2**100

13
[jytliszt jyt℄$ ./a.py
1267650600228229401496703205376
ou faire exé uter des  hiers
[jytliszt jyt℄$ at b.py
print 2**100
[jytliszt jyt℄$ python b.py
1267650600228229401496703205376

[jytliszt jyt℄$ e ho "print 2**100"|python


1267650600228229401496703205376

14
Conventions essentiellement omme en C

>>> a=2
>>> a
2
>>> 1 == 2
False
>>> print "%s = %f" % ("pi", 3.1415926)
pi = 3.141593
Mais ...

15
... il y a un piège

Les variables sont des référen es à des objets. Si b = a,


une modi ation de a peut ae ter b :
>>> a=2
>>> b=a
>>> a=3
>>> b
2 # jusqu'i i, RAS ...
>>> a=[1,2,3℄
>>> b=a
>>> a[1℄=5
>>> b
[1, 5, 3℄ # aïe aïe aïe !

16
Solution : le module opy

Pas gênant si on est ons ient du problème.


>>> help(' opy')
>>> import opy
>>> x=[1,2,3℄
>>> y= opy. opy(x)
>>> y
[1, 2, 3℄
>>> x[1℄=5
>>> x
[1, 5, 3℄
>>> y
[1, 2, 3℄

17
Pour les objets omplexes, utiliser deep opy

>>> u=[1,[2,3℄,4℄
>>> v= opy. opy(u)
>>> u[0℄=6
>>> u
[6, [2, 3℄, 4℄
>>> v
[1, [2, 3℄, 4℄
>>> u[1℄[0℄=7
>>> u
[6, [7, 3℄, 4℄
>>> v
[1, [7, 3℄, 4℄

18
>>> p=[1, [2,[3,4℄,5℄, [6,7℄℄
>>> q= opy.deep opy(p)
>>> p[1℄[1℄[0℄=8
>>> p
[1, [2, [8, 4℄, 5℄, [6, 7℄℄
>>> q
[1, [2, [3, 4℄, 5℄, [6, 7℄℄

19
Blo s et indentation

Pas d'a olades ou de begin/end. C'est l'indentation qui


détermine la stru ture des blo s :
>>> for i in range(0,256):
... if hr(i).isalnum():
... print i, hr(i)
... else: pass
Le point-virgule en n de ligne est optionnel. On peut l'utiliser
pour mettre plusieurs instru tions par ligne :
>>> x='abra'; y=' adabra'; z=x+y; print z
abra adabra

20
On peut utiliser des \ pour ontinuer une instru tion sur la
ligne suivante :
print 2+3*4/27% \
42+37
Il est parfois plus simple (et re ommandé) d'utiliser des
parenthèses :
print (2+3*4/27
%42+37)

21
Stru tures onditionnelles, bou les

if ondition: si_vrai()
elif: autre_tru ()
else: si_faux()

while ondition:
iteration()
if fini: break
if pouet: ontinue
autre_ hose()

22
for element in liste:
manip(element)
if foo(element): break
if quux(element): ontinue
hose(element)

>>> range(0,10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9℄
>>> for i in range(0,10): print i**2

23
Les types : entiers et ottants

>>> 2+3*4
14
>>> 1<<8
256
>>> 5**3
125
>>> 42%10
2
>>> 2**30
1073741824
>>> 2**31, 2**100
(2147483648L, 1267650600228229401496703205376L)

24
>>> import math
>>> math. os(math.pi/3)
0.50000000000000011
>>> 2**(1.0/12)
1.0594630943592953
>>> 2**(1/12)
1
>>> 1/12
0
>>> int("0256")
256
>>> int("1101101",2)
109
>>> hex(_)
'0x6d'
>>> int(_,16)
109
25
>>> from de imal import *
>>> get ontext()
Context(pre =28, rounding=ROUND_HALF_EVEN,
Emin=-999999999, Emax=999999999,
apitals=1, flags=[℄,
traps=[Overflow, InvalidOperation, DivisionByZero℄)
>>> get ontext().pre =100
>>> De imal(2).sqrt()
De imal("1.414213562373095048801688724209698078569671875376948\
073176679737990732478462107038850387534327641573")
>>>

26
Les types : haînes

>>> "ab "+"def"


'ab def'
>>> "ab "*2
'ab ab '
>>> "ab %sdef%d" % ("toto",4)
'ab totodef4'
>>> "%08X" % 42069
'0000A455'
>>> "%%%s" % "d" % 12
12
>>> "ra " in "abra adabra"
True

27
>>> len("toto")
4
>>> "toto".upper()
'TOTO'
>>> " x yz ".strip()
'x yz'
>>> "albert".startswith("al")
True
>>> "salamale ".repla e("al","ila")
'silaamilae '
>>> "l'an de l'ananas". ount("an")
3
>>> " piano\n".strip()
'piano'

28
Les types : tuples et listes

>>> [1,2,4,8℄+[16,32℄
[1, 2, 4, 8, 16, 32℄
>>> (1,2,3)*2
(1, 2, 3, 1, 2, 3)
>>> liste=["toto",42,True℄
>>> liste[0℄=123
>>> liste
[123, 42, True℄
>>> 123 in liste
True
>>> 123 not in liste
False

29
>>> pasliste=(1, False)
>>> pasliste[0℄
1
>>> pasliste[0℄=69
TypeError: obje t doesn't support item assignment
>>> list(pasliste)
[1, False℄
>>> range(4)
[0, 1, 2, 3℄
>>> tuple(range(4))
(0, 1, 2, 3)

30
Les types : di tionnaires

>>> bazar={"e": 2.71828, "jaune": (255,255,0), "vrai": True,


10: "dix", "liste": [4, 2, {False: "faux"}℄, (0,0):"origine"}
>>> bazar["liste"℄
[4, 2, {False: "faux"}℄
>>> bazar["liste"℄[2℄[False℄
'faux'
>>> bazar.has_key("tru ")
False
>>> bazar["tru "℄=" hose"
>>> "tru " in bazar
True
>>> del bazar["tru "℄
>>> di t([("k1",10),("k2","v")℄)

31
>>> "ab defgihj"[4℄
'e'
>>> "ab defghij"[4:7℄
'efg'
>>> [1,2,4,8,16℄[2:℄
[4, 8, 16℄
>>> s="ga bu zo meu"
>>> s[-3:℄
'meu'
>>> s = s.split(" ")
>>> s
['ga', 'bu', 'zo', 'meu'℄
>>> "_".join([x*2 for x in s℄)
'gaga_bubu_zozo_meumeu'

32
Le typage en Python

Typage dynamique : les types sont impli itement polymorphes


On peut sur harger les opérateurs
Du k typing : Connaître le type d'un objet n'a pas
d'importan e, il faut seulement s'assurer qu'on peut lui
appliquer les traitements souhaités
"si ça mar he omme un anard et si ça an ane omme un
anard, alors e doit être un anard"

33
Polymorphisme :
>>> def add(a,b): return a+b
>>> add(3,5)
8
>>> add(3,5.0)
8.0
>>> add("abra"," adabra")
'abra adabra'
>>> add([1,2℄,[3,4℄)
[1, 2, 3, 4℄
>>>

34
>>> print type(5), type(5.0), type("abra"),type([1,2℄)
<type 'int'> <type 'float'> <type 'str'> <type 'list'>
>>> 2+"2"
Tra eba k (most re ent all last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 2*"2"
'22'

35
>>> lass Cbase: pass
>>> lass Cderivee(Cbase): pass
>>> Ibase=CBase() ; Iderivee=Cderivee()
>>> isinstan e(Ibase,Cbase)
True
>>> isinstan e(Iderivee,Cbase)
True
>>> isinstan e(Ibase,Cderivee)
False
>>> allable(42), allable(Cbase)
(False, True)

36
Fon tions

def aire(x1,y1,x2,y2):
delta_x=x2-x1
delta_y=y2-y1
return abs(delta_x*delta_y)

def aire(a,b,x2=None,y2=None):
if x2: x1,y1=a,b
else: (x1,y1),(x2,y2)=a,b
return abs((x2-x1)*(y2-y1))
La deuxième version mar he ave aire(1,2,3,4) mais aussi
aire((1,2),(3,4))

37
Fon tions ave arguments nommés

def wget(host,port=80,uri="/"):
return urllib.urlopen("http://%s:%d%s"%(host,port,uri)).read()

wget("google. om")
wget("google. om",80,"/sear h?q=perdu")
wget("google. om",uri="/sear h?q=perdu")
wget(uri="/sear h?q=perdu",host="google. om")

Interdit : fon tion(param=valeur,autreparam)

38
Fon tions variadiques

def printf(format_string, *args):


print format_string % args

printf("%s: %d","trois",3)

liste=["riri", "fifi", "loulou", 17℄


printf("%s + %s + %s = %d",*liste)

toto(a,b, ) = toto(*[a,b, ℄)

39
Arguments nommés arbitraires

def apply_font(font="Helveti a", size=12, **styles):


print "Font name is %s."%font; print "Font size is %d."%size
print "Extra attributes:"
for attrname,attrvalue in styles.items():
print "\t%s: %s"%(attrname,str(attrvalue))

>>> apply_font(size=24, olor="red",ba kground="bla k")


Font name is Helveti a.
Font size is 24.
Extra attributes:
ba kground: bla k
olor: red
>>> apply_font(**{" olor": "red", "ba kground": "bla k"})

40
Fon tions anonymes

>>> ompose=lambda f,g:lambda x:g(f(x))


>>> plus4fois2= ompose(lambda x:x+4,lambda x:x*2)
>>> plus4fois2(5)
18
Vient du LISP. Utilité : map et filter
>>> map(lambda x: x*x, [1,2,3,4℄)
[1, 4, 9, 16℄
>>> filter(lambda x: hr(x).isdigit(), range(0,256))
[48, 49, 50, 51, 52, 53, 54, 55, 56, 57℄

41
Compréhension de listes

Syntaxe laire et e iente, empruntée à Haskell.


Rempla e avantageusement lambda, map, filter.
>>> [x*x for x in [1,2,3,4℄℄
[1, 4, 9, 16℄

>>> [x for x in range(0,256) if hr(x).isdigit()℄


[48, 49, 50, 51, 52, 53, 54, 55, 56, 57℄

>>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)℄


>>> primes = [x for x in range(2, 50) if x not in noprimes℄
>>> print primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47℄

42
Qui ksort en 2 lignes

def q(L):
if len(L)<= 1: return L
return q([x for x in L[1:℄ if x<L[0℄℄)+[L[0℄℄+q([y for y in L[1:℄ if y>=L[0℄℄)

>>> ll
[78, 46, 63, 20, 53, 10, 26, 52, 41, 54, 81, 75, 49, 21, 80, 60, 58, 56, 86,
40, 95, 92, 0, 4, 77, 12, 5, 59, 90, 57, 71, 3, 65, 27, 97, 89, 19, 38, 15, 85,
6, 62, 11, 33, 67, 61, 73, 44, 50, 17, 94, 48, 43, 34, 55, 24, 87, 70, 2, 16,
42, 25, 37, 68, 88, 30, 23, 7, 83, 74, 84, 39, 32, 98, 99, 22, 1, 45, 82, 69, 96,
31, 51, 91, 14, 13, 66, 36, 9, 18, 8, 79, 47, 72, 29, 76, 93, 64, 28, 35℄
>>> q(ll)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99℄
>>>

43
Extra tion express d'une onguration

>>> d=di t([kv.split("=",1)


for kv in open("/et /libuser. onf").read().split("\n")
if "=" in kv and not kv.strip().startswith("#")℄)
>>> d
{'LU_GIDNUMBER ': ' 500', 'mailspooldir ': ' /var/mail',
'moduledir ': ' /usr/lib/libuser', 'modules ': ' files shadow',
'skeleton ': ' /et /skel', ' reate_modules ': ' files shadow',
'LU_UIDNUMBER ': ' 500', 'LU_USERNAME ': ' %n',
'LU_GROUPNAME ': ' %n', ' rypt_style ': ' md5'}

44
Ex eptions - 1

try:
buffer += so ket.read(4096)
# ...
ex ept OSError,e:
if e.errno!=errno.EAGAIN: raise
ex ept DiskFullEx eption:
print "Le disque est plein."
ex ept:
save_the_work()
do_something_with(sys.ex _tra eba k)

45
Ex eptions - 2

try:
du_ ode()
raise Ex eption # ex eption générique
#raise Ex eption('message expli atif') # un peu mieux
#raise NetworkEx eption( lientso ket, errno) # par exemple..
ex ept NetworkEx eption:
...
ex ept Ex eption:
...

46
Ex eptions - 3

try:
du_ ode()
raise Ex eption("bonjour")
finally:
# sera exé uté dans tous les as
# (et avant les éventuels handlers d'ex eption)
save_work_in_progress()
print "au revoir"

47
Commentaires et do strings

# ave des dièses


"ou bien des haînes littérales"

""" ou en ore, sur plusieurs lignes,


ave des triple-quotes """

def ra ine_ arree(x):


"""Cette fon tion al ule la ra ine arrée
du nombre fourni omme paramètre."""
return x**0.5

help(ra ine_ arree)


help.__do __

48
L'itération en Python

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9℄
>>> [x*x for x in range(10)℄
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81℄
>>> [x*x for x in range(10) if x%2℄
[1, 9, 25, 49, 81℄
>>> map(lambda x:x*x, range(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81℄
>>> filter(lambda x:x%2,[1, 4, 2, 3, 7, 8, 13, 42℄)
[1, 3, 7, 13℄
>>> h={"un":1, "deux":2, "trois":3}
>>> for key in h: print key,
un trois deux

49
Générateurs
def fib():
a, b = 0, 1
while 1:
yield b; a, b = b, a+b

>>> F=fib()
>>> F.next()
1
>>> F.next()
1
>>> F.next()
2
>>> F.next()
3
50
>>> for (i, f) in zip(range(10), fib()): print "F[%d℄=%d" % (i, f)
...
F[0℄=1
F[1℄=1
F[2℄=2
F[3℄=3
F[4℄=5
F[5℄=8
F[6℄=13
F[7℄=21
F[8℄=34
F[9℄=55
>>> zip("abra adabra", range(6))
[('a', 0), ('b', 1), ('r', 2), ('a', 3), (' ', 4), ('a', 5)℄

51
Aide mémoire : dir()

>>> dir()
['__builtins__', '__do __', '__name__', '__pa kage__', 'readline', 'rl ompleter'℄
>>> dir("")
['__add__', '__ lass__', '__ ontains__', '__delattr__', '__do __', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getsli e__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
'__mod__', '__mul__', '__ne__', '__new__', '__redu e__', '__redu e_ex__',
'__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__',
'__sub lasshook__', '_formatter_field_name_split', '_formatter_parser',
' apitalize', ' enter', ' ount', 'de ode', 'en ode', 'endswith', 'expandtabs',
'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspa e',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'repla e',
'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swap ase', 'title', 'translate', 'upper', 'zfill'℄
>>>

52

Anda mungkin juga menyukai