rep = input("Est-ce vivant ? [oui/non] ")
while rep not in ['oui', 'non']:
rep = input("Réponse incorrecte, répondre 'oui' ou 'non' : ")
if rep == 'oui':
vivant = True
if rep == 'non':
vivant = False
rep = input('Est-ce un animal ? [oui/non] ')
while rep not in ['oui', 'non']:
rep = input("Réponse incorrecte, répondre 'oui' ou 'non' : ")
if rep == 'oui':
animal = True
if rep == 'non':
animal = False
Est-ce vivant ? [oui/non] oui Est-ce un animal ? [oui/non] peut-être Réponse incorrecte, répondre 'oui' ou 'non' : oui
if vivant:
if animal: print("Un tigre !")
else: print("Un champignon !")
else:
if animal: print("Paf le chien !")
else: print("Un bilboquet !")
Un tigre !
def reponse(question):
"Renvoie la réponse à la question"
rep = input(question + ' [oui/non] ')
while rep not in ['oui', 'non']:
rep = input("Réponse incorrecte, répondre 'oui' ou 'non' : ")
if rep == 'oui':
return True
if rep == 'non':
return False
vivant = reponse("Est-ce vivant ?")
animal = reponse("Est-ce un animal ?")
Est-ce vivant ? [oui/non] non Est-ce un animal ? [oui/non] oui
def reponse(question):
rep = input(question + ' [o/n] ')
while rep not in ['o', 'n']:
rep = input("Réponse incorrecte, répondre 'o' ou 'n' : ")
if rep == 'o':
return True
if rep == 'n':
return False
vivant = reponse("Est-ce vivant ?")
animal = reponse("Est-ce un animal ?")
Est-ce vivant ? [o/n] n Est-ce un animal ? [o/n] n
def nom_de_la_fonction(parametre1, parametre2):
"Documentation de la fonction"
# Liste d'instructions :
valeur_de_retour = parametre1 * parametre2
return valeur_de_retour
nom_de_la_fonction(32, 52) # Appel avec deux arguments
1664
Une fonction prend des arguments et renvoie une valeur de retour.
ATTENTION : affichage ≠ valeur de retour !
def prod(a, b):
print(a*b)
x = prod(3, 17)
print("Résultat :", x)
51 Résultat : None
return ...
: sortie de la fonctionreturn None
implicite à la toute fina = 12
def globale():
print(a)
globale()
a
12
12
a = 12
def locale():
a = 1
print(a)
locale()
a
1
12
a = 12
def explicitement_globale():
global a
a = 1
explicitement_globale()
a
1
a = 12
def attention():
print(a)
a = 1
attention() # Boum !
--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) <ipython-input-13-65220c0eab2d> in <module>() 3 print(a) 4 a = 1 ----> 5 attention() # Boum ! <ipython-input-13-65220c0eab2d> in attention() 1 a = 12 2 def attention(): ----> 3 print(a) 4 a = 1 5 attention() # Boum ! UnboundLocalError: local variable 'a' referenced before assignment
** Par défaut (en Python) :**
Mais
global
nonlocal
a = 12
def u():
def v():
a = 1
print("Dans v :", a)
a = 2
v()
print("Dans u :", a)
u()
a
Dans v : 1 Dans u : 2
12
a = 12
def u():
def v():
global a
a = 1
print("Dans v :", a)
a = 2
v()
print("Dans u :", a)
u()
a
Dans v : 1 Dans u : 2
1
a = 12
def u():
global a
def v():
a = 1
print("Dans v :", a)
a = 2
v()
print("Dans u :", a)
u()
a
Dans v : 1 Dans u : 2
2
a = 12
def u():
def v():
nonlocal a
a = 1
print("Dans u :", a)
a = 2
v()
print("Dans v :", a)
u()
a
Dans u : 1 Dans v : 1
12
def carre(x):
x = x**2
return x
def carres(L):
for i in range(len(L)):
L[i] = L[i]**2
return L
x = 5
y = carre(x)
x, y
(5, 25)
L = [1, 2, 3]
M = carres(L)
L, M
([1, 4, 9], [1, 4, 9])
Python :
Immuable :
int
, float
, bool
, complex
, ...tuple
: (1, 2, 3)
) et chaînes (str
: "abc"
)Variable :
list
: [1, 2, 3]
), dictionnaires (dict
: {1:'a', 2:'b'}
), ensembles (set
: {1, 2, 3}
)def modifie(L):
L[0] = 0
print(L)
L = [1, 2, 3]
modifie(L)
L
[0, 2, 3]
[0, 2, 3]
def conserve(L):
L = [0] + L[1:]
print(L)
L = [1, 2, 3]
conserve(L)
L
[0, 2, 3]
[1, 2, 3]
Remarque : pas de t[i] = j
pour un uplet ou une chaîne !
def fact(n):
if n < 2: # Cas de base
return 1
return n * fact(n-1) # Appel sur un argument plus petit
fact(5)
120
def pair(n):
if n == 0: return True
return impair(n-1)
def impair(n):
if n == 0: return False
return pair(n-1)
pair(17)
False
Terminaison : récurrence (paramètres plus petits + cas de base)
Correction : récurrence avec initialisation = cas de base
Complexité : équations de récurrence (cf cours précédent)
fact
: « pour tout $n\ge 0$, fact(n)
renvoie $n!$. »
fact(n-1)
renvoie $(n-1)!$, fact(n)
renvoie $n\times (n-1)! = n!$(im)pair
: « $\forall n$, pair(n)
et impair(n)
sont correctes »
impair(n-1)
correct, pair(n)
renvoyant impair(n-1)
est correct. Idem pour impair(n)
.def itere(f, x, n):
"Renvoie f(f(f(...(f(x))))), n fois"
if n == 0:
return x
return itere(f, f(x), n-1)
def suivant(x): return x+1
def addition(a, b):
return itere(suivant, a, b)
addition(18, 33)
51
map
:list(map(suivant, [1, 2, 3]))
[2, 3, 4]
lambda
et fonctions anonymes¶lambda x:2*x
(remarque : pas de return
)lambda t : t if t > 0 else -t
valeur_absolue = lambda t : t if t > 0 else -t
valeur_absolue(-6)
6
itere(lambda t: 2*t, 1, 10)
1024
list(map(lambda x: x[0], [(1,3),(7,5)])) # eq. à [x[0] for x in [...]]
[1, 7]
def f(x, y, z = 3, t = 5):
return (x,y,z,t)
f(1, 2, 1, 1)
(1, 2, 1, 1)
f(1, 2)
(1, 2, 3, 5)
f(1, 2, 1)
(1, 2, 1, 5)
f(1, 2, t = 1)
(1, 2, 3, 1)
f(1, 2, t = 3, z = 5)
(1, 2, 5, 3)
f(t = 1, z = 2, y = 3, x = 4)
(4, 3, 2, 1)
*args
: tuple
d'arguments non nommés**kwargs
: dict
d'arguments nommésargs
et kwargs
standards, mais pas *foo
, **bar
ou *toto
marchent !def g(x, y = 100, *args, z = 200, **kwargs):
print('x : {} ; y : {} ; z : {}'.format(x,y,z))
print('*args : ', args)
print('**kwargs : ', kwargs)
g(1, 2, 3, 4, 5, a=6, b=7)
x : 1 ; y : 2 ; z : 200 *args : (3, 4, 5) **kwargs : {'a': 6, 'b': 7}
g(1, t = 4)
x : 1 ; y : 100 ; z : 200 *args : () **kwargs : {'t': 4}
g(1, 2, y = 3, a = 4)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-56-914cd2b97687> in <module>() ----> 1 g(1, 2, y = 3, a = 4) TypeError: g() got multiple values for argument 'y'
def racine(x, n = 2):
"""
Renvoie la (partie entière de la) racine n-ème de x.
Par défaut n vaut 2.
"""
k = 0
while k**n <= x:
k += 1
return k - 1
help(racine)
Help on function racine in module __main__: racine(x, n=2) Renvoie la (partie entière de la) racine n-ème de x. Par défaut n vaut 2.