Intro à Python

Denys Duchier

Documents


utiliser python intéractivement

$ python3
Python 3.2.3 (default, May  3 2012, 01:49:54) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 

Types élémentaires de données

  • Entiers
  • Flottants
  • Booléens
  • Chaînes
  • None

Types élémentaires de données

Entiers

>>> 23
23
>>> print(23)
23
>>> type(23)
<class 'int'>
>>> 

Types élémentaires de données

Flottants

>>> 23.4
23.4
>>> print(23.4)
23.4
>>> type(23.4)
<class 'float'>
>>> 

Types élémentaires de données

Booléens

>>> True
True
>>> False
False
>>> print(True,False)
True False
>>> type(True)
<class 'bool'>
>>> 

Types élémentaires de données

Chaînes

>>> "hello"
'hello'
>>> print("hello")
hello
>>> type("hello")
<class 'str'>
>>> 

Types élémentaires de données

None

>>> None
>>> print(None)
None
>>> type(None)
<class 'NoneType'>
>>> 
  • semblable à void en C++

Expressions

>>> 1+3
4
>>> 12.3+23.4
35.7
>>> "hello"+"world"
'helloworld'
>>> True+False
1
>>> 

Expressions

>>> 1 + 2.3
3.3
>>> True + 2.3
3.3
>>> "hello" + 12
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>> 

Expressions

>>> 2*3
6
>>> 2.3*3.4
7.819999999999999
>>> 2*3.4
6.8
>>> 2*"hello"
'hellohello'
>>> "hello"*"world"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
>>> 

Variables

>>> x=1
>>> print(x)
1
>>> x="hello"
>>> print(x)
hello
>>> x
'hello'
>>> x=2
>>> y=23.4
>>> x*y
46.8
>>> 

Fonctions

>>> def moyenne(a,b):
...   return (a+b)/2
... 
>>> moyenne(2,5)
3.5
>>> 


  • les blocs sont marqués par l'indentation en python, au lieu de { ... } en C++

Conditionelles

>>> def factorielle(n):
...   if n<=1:
...     return 1
...   else:
...     return n*factorielle(n-1)
... 
>>> factorielle(5)
120
>>> 

Expressions Booléennes


e1 and e2
e1 or e2
not e
( e )

Boucles for

>>> for i in range(5):
...   print(i)
... 
0
1
2
3
4
>>> range(5)
range(0, 5)
>>> 
    

  • il y a aussi une boucle while

Boucles for

>>> for i in range(1,5):
...   print(i)
... 
1
2
3
4
>>> for i in range(1,5,2):
...   print(i)
... 
1
3
>>> 
    

Fonctions et variables locales

>>> def fact(n):
...   r=1
...   for i in range(1,n+1):
...     r *= i
...   return r
... 
>>> fact(5)
120
>>> 
  • les variables locales sont:
    • les parametres
    • les variables localement affectées

Listes

>>> [1,2,3]
[1, 2, 3]
>>> [1,2.3,True,"hello"]
[1, 2.3, True, 'hello']
>>> [1,["hello",2.4],False]
[1, ['hello', 2.4], False]
>>> [[1,2,3],
...  [4,5,6]]
[[1, 2, 3], [4, 5, 6]]
>>> 

  • une liste peut contenir des éléments de types différents
  • un tableau à plusieurs dimensions peut être représenté par des listes imbriquées

Listes

Consultation

>>> x=[1,2.3,[True,"hello"]]
>>> x
[1, 2.3, [True, 'hello']]
>>> x[0]
1
>>> x[1]
2.3
>>> x[2]
[True, 'hello']
>>> x[2][0]
True
>>> x[2][1]
'hello'
>>> x[2][1][0]
'h'
>>> x[2][1][1]
'e'
>>> len(x)
3
>>>

Listes

Consultation

>>> for i in range(len(x)):
...   print(x[i])
... 
1
2.3
[True, 'hello']
>>> for v in x:
...   print(v)
... 
1
2.3
[True, 'hello']
>>>
  • les listes sont itérables

Listes

Consultation

>>> def moy(l):
...   r=0
...   for x in l:
...     r += x
...   return r/len(l)
... 
>>> moy([1,3,6])
3.3333333333333335
>>>

Listes

Modification

>>> x[0]=[]
>>> x
[[], 2.3, [True, 'hello']]
>>> x.append("more")
>>> x
[[], 2.3, [True, 'hello'], 'more']
>>> x.pop()
'more'
>>> x
[[], 2.3, [True, 'hello']]
>>> x.pop()
[True, 'hello']
>>> x
[[], 2.3]
>>>

Listes

Modification

>>> x=[1,2]
>>> y=[x,x]
>>> y
[[1, 2], [1, 2]]
>>> y[0]
[1, 2]
>>> y[0][0]
1
>>> y[0][0]="hello"
>>> y
[['hello', 2], ['hello', 2]]
>>>
  • 2 fois le même objet liste (x) dans y (partage!)

Listes

Accès avancé

>>> x
['hello', 2]
>>> x[-1]
2
>>> x[-2]
'hello'
>>>

  • indices négatifs pour l'accès en partant de la fin

Listes

Accès avancé

>>> x=[12,23,34,45,56]
>>> x[0]
12
>>> x[-1]
56
>>> x[1:3]
[23, 34]
>>> x[:3]
[12, 23, 34]
>>> x[1:]
[23, 34, 45, 56]
>>> x[:]
[12, 23, 34, 45, 56]
>>>
  • on peut prendre des slices (tranches) de liste

Listes

Accès avancé

>>> x
[12, 23, 34, 45, 56]
>>> y=x[:]
>>> y
[12, 23, 34, 45, 56]
>>> x[0]="hello"
>>> x
['hello', 23, 34, 45, 56]
>>> y
[12, 23, 34, 45, 56]
>>>
  • une slice crée une copie

Listes

Test d'appartenance

>>> def membre(x,l):
...   for y in l:
...     if x==y:
...       return True
...   return False
... 
>>> x
['hello', 23, 34, 45, 56]
>>> membre(2,x)
False
>>> membre(45,x)
True
>>>

Listes

Test d'appartenance

>>> def membre2(x,l):
...   return x in l
... 
>>> membre(2,x)
False
>>> membre(45,x)
True
>>>

  • l'opérateur infixe in permet aussi de tester l'appartenance

Listes

Notation dite en compréhension

example traditionel:

>>> def doubles(l):
...   r=[]
...   for x in l:
...     r.append(2*x)
...   return r
... 
>>> y
[12, 23, 34, 45, 56]
>>> doubles(y)
[24, 46, 68, 90, 112]
>>>

Listes

Notation dite en compréhension

example en compréhension:

>>> def doubles2(l):
...   return [2*x for x in l]
... 
>>> y
[12, 23, 34, 45, 56]
>>> doubles2(y)
[24, 46, 68, 90, 112]
>>>

Listes

Notation dite en compréhension

liste des doubles des élements pairs:

>>> def dpair(l):
...   return [2*x for x in l if x%2==0]
... 
>>> y
[12, 23, 34, 45, 56]
>>> dpair(y)
[24, 68, 112]
>>>

Listes

Notation dite en compréhension

liste des couples possibles d'une liste:

>>> def couples(l):
...   return [(x,y) for x in l for y in l]
... 
>>> y
[12, 23, 34, 45, 56]
>>> couples(y)
[(12, 12), (12, 23), (12, 34), (12, 45), (12, 56), (23, 12), (23, 23), (23, 34), (23, 45), (23, 56), (34, 12), (34, 23), (34, 34), (34, 45), (34, 56), (45, 12), (45, 23), (45, 34), (45, 45), (45, 56), (56, 12), (56, 23), (56, 34), (56, 45), (56, 56)]
>>>

Listes

Notation dite en compréhension

liste des couples possibles pair/impair:

>>> def pairimpair(l):
...   return [(x,y) for x in l if x%2==0
...                 for y in l if y%2==1]
... 
>>> y
[12, 23, 34, 45, 56]
>>> pairimpair(y)
[(12, 23), (12, 45), (34, 23), (34, 45), (56, 23), (56, 45)]
>>>

Tuples

>>> (1,2,3)
(1, 2, 3)
>>> x=(1,2,3)
>>> x
(1, 2, 3)
>>> type(x)
<class 'tuple'>
>>> x[0]
1
>>> x[0]=5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>

  • contrairement à une liste, un tuple n'est pas modifiable

Tuples

>>> ()
()
>>> (1)
1
>>> (1,)
(1,)
>>> type(())
<class 'tuple'>
>>> type((1))
<class 'int'>
>>> type((1,))
<class 'tuple'>
>>> type((1,2))
<class 'tuple'>
>>>

Tuples

>>> len(())
0
>>> len((1,))
1
>>> len((1,2,))
2
>>> len((1,2))
2
>>> (1,2)==(1,2,)
True
>>>

Tuples

>>> x=(1,2,3)
>>> for v in x:
...   print(v)
... 
1
2
3
>>> for v in "hello":
...   print(v)
... 
h
e
l
l
o
>>>
  • tuple et string sont itérables

Dicts

>>> x={"un": 11, "deux": 222, 3: "trois"}
>>> x
{3: 'trois', 'un': 11, 'deux': 222}
>>> x["un"]
11
>>> x["deux"]
222
>>> x[3]
'trois'
>>> x["quatre"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'quatre'
>>>
  • un dict est une table associative

Dicts

>>> x["quatre"]=4
>>> x
{3: 'trois', 'un': 11, 'quatre': 4, 'deux': 222}
>>> x["quatre"]
4
>>> len(x)
4
>>> x
{3: 'trois', 'un': 11, 'quatre': 4, 'deux': 222}
>>> del x[3]
>>> x
{'un': 11, 'quatre': 4, 'deux': 222}
>>> len(x)
3
>>>

Dicts

>>> for k in x:
...   print(k)
... 
un
quatre
deux
>>> for v in x.items():
...   print(v)
... 
('un', 11)
('quatre', 4)
('deux', 222)
>>> for k,v in x.items():
...   print(k,"->",v)
... 
un -> 11
quatre -> 4
deux -> 222
>>>

Dicts

>>> "deux" in x
True
>>> "hello" in x
False
>>>

Dicts

>>> def ddoubles(d):
...   r={}
...   for k,v in d.items():
...     r[k] = 2*v
...   return r
... 
>>> x
{'un': 11, 'quatre': 4, 'deux': 222}
>>> ddoubles(x)
{'un': 22, 'quatre': 8, 'deux': 444}
>>>

Dicts

>>> def ddoubles2(d):
...   return {k: 2*v for k,v in d.items()}
... 
>>> x
{'un': 11, 'quatre': 4, 'deux': 222}
>>> ddoubles2(x)
{'un': 22, 'quatre': 8, 'deux': 444}
>>>

Scripts et Modules

Fichier ex1.py

def fact(n):
    r=1
    for i in range(2,n+1):
        r*=i
    return r

print(fact(5))

Dans un terminal

$ python3 ex1.py
120
$

Scripts et Modules

Fichier factlib.py

def fact(n):
    r=1
    for i in range(2,n+1):
        r*=i
    return r

Fichier ex2.py

import factlib

print(factlib.fact(5))

Scripts et Modules

Fichier factlib.py

def fact(n):
    r=1
    for i in range(2,n+1):
        r*=i
    return r

Fichier ex3.py

from factlib import fact

print(fact(5))

Systèmes de Lindenmayer

Snake

Systèmes de Lindenmayer

Snake

Règles de dessin

-  tourner à droite
+  tourner à gauche
f  avancer
b  f+f+f--f--f+f+f

Règles de remplacement

b  b+f+b--f--b+f+b

État initial

b--f--b--f

Systèmes de Lindenmayer

Snake

  • on utilise les règles de remplacement pour réécrire l'état initial jusqu'à une certaine profondeur de réccursion

  • puis on utilise les règles de dessin pour dessiner le résultat

Systèmes de Lindenmayer

Snake

# -*- coding: utf-8 -*-
from turtle import *

def droite():
    right(45)
#    color("yellow")

def gauche():
    left(45)
#    color("red")

def avance():
    forward(7.5)

règles_de_dessin = {
    "-": droite,
    "+": gauche,
    "f": avance,
    "b": "f+f+f--f--f+f+f" }

règles_de_remplacement = {
    "b": "b+f+b--f--b+f+b" }

état_initial = "b--f--b--f"

def dessiner(état,n):
    for c in état:
        c = remplacer(c,n)
        if isinstance(c,str):
            for x in c:
                dessiner(x,n-1)
        else:
            c()

def remplacer(c,n):
    if n<=0 or c not in règles_de_remplacement:
        return règles_de_dessin[c]
    else:
        return règles_de_remplacement[c]

goto(-200,0)
clear()
speed(20)
dessiner(état_initial, 3)
done()

Systèmes de Lindenmayer

Krishna

Systèmes de Lindenmayer

Krishna

# -*- coding: utf-8 -*-
from turtle import *
from math import sqrt

def A():
    color("red")
    circle(10,90)

def B():
    color("black")
    l = 5/sqrt(2)
    forward(l)
    circle(l, 270)
    forward(l)

def F():
    color("green")
    forward(10)

règles_de_dessin = {
    "a": A,
    "b": B,
    "f": F }

règles_de_remplacement = {
    "a": "afbfa",
    "b": "afbfbfbfa" }

état_initial = "fbfbfbfb"

def dessiner(état, n):
    for c in état:
        c = remplacer(c,n)
        if isinstance(c,str):
            for x in c:
                dessiner(x,n-1)
        else:
            c()

def remplacer(c,n):
    if n<=0 or c not in règles_de_remplacement:
        return règles_de_dessin[c]
    else:
        return règles_de_remplacement[c]

goto(-45,0)
clear()
speed(20)
dessiner(état_initial, 3)
done()