Jean-Yves Thibon
Université Paris-Est Marne-la-Vallée
http://igm.univ-mlv.fr/∼ jyt
Python
1
CPython
2
Jpython (ex Jython)
3
Bref historique
4
Cara
téristiques du langage
5
Des types de données de haut niveau
6
Exemples
7
Plus instru
tif ...
#!/usr/bin/python
'''hello.py: le programme 'Hello world' bien
onnu.
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()
9
Qui utilise Python ?
10
The Zen of Python
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
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
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
16
Solution : le module
opy
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
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
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
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
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")
38
Fon
tions variadiques
printf("%s: %d","trois",3)
toto(a,b, ) = toto(*[a,b, ℄)
39
Arguments nommés arbitraires
40
Fon
tions anonymes
41
Compréhension de listes
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
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
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