3. Contrôle de Flux
if/elif/else,for,while,match/case(3.10+),break,continue,elsesur boucles.
3.1 Conditionnel
x = 42
if x > 100:
print("Grand")
elif x > 10:
print("Moyen")
else:
print("Petit")Expression conditionnelle (ternaire) :
status = "pair" if x % 2 == 0 else "impair"3.2 Boucle while
i = 0
while i < 5:
print(i)
i += 13.3 Boucle for
Parcourt un itérable :
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 8, 2): # 2, 4, 6 (start, stop, step)
print(i)fruits = ["pomme", "banane", "cerise"]
for fruit in fruits:
print(fruit)3.4 break, continue, else
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
break
else:
print(f"{n} est premier") # else après boucle = pas de breakLe else sur une boucle s’exécute si aucun break n’a eu lieu.
3.5 match/case (Python 3.10+)
Pattern matching structurel :
def décrire(valeur):
match valeur:
case 0:
return "Zéro"
case 1 | 2 | 3:
return "Petit"
case int() as n if n > 100:
return f"Grand: {n}"
case [x, y]:
return f"Paire: {x}, {y}"
case {"nom": n, "âge": a}:
return f"{n}, {a} ans"
case _:
return "Autre"3.6 range()
list(range(5)) # [0, 1, 2, 3, 4]
list(range(1, 5)) # [1, 2, 3, 4]
list(range(0, 10, 2)) # [0, 2, 4, 6, 8]
list(range(5, 0, -1)) # [5, 4, 3, 2, 1]3.7 enumerate() et zip()
for i, fruit in enumerate(fruits):
print(i, fruit)
noms = ["Alice", "Bob"]
âges = [30, 25]
for nom, âge in zip(noms, âges):
print(f"{nom}: {âge} ans")