Corrigés des exercices
Python : de la base à la POO
Ce document contient les corrigés du guide python_base.tex. Chaque exercice correspond au
même numéro dans le cours principal (ordre des sections aligné sur le cours : chaînes puis saisie puis
opérateurs ; exercice 7.4 majeur/mineur ; ainsi que 12.2–12.3, 13.2, 14.2). Les solutions sont données
en code Python prêt à être enregistré dans un fichier .py et exécuté.
Table des matières
1 Section 1 — Installer Python 3
1.1 Exercice 1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 Section 2 — Variables 3
2.1 Exercice 2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 Exercice 2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3 Section 3 — Types 3
3.1 Exercice 3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3.2 Exercice 3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
4 Section 4 — Chaînes 3
4.1 Exercice 4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
4.2 Exercice 4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
4.3 Exercice 4.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
5 Section 5 — Saisie au clavier 4
5.1 Exercice 5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
5.2 Exercice 5.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
5.3 Exercice 5.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
6 Section 6 — Opérateurs et expressions 4
6.1 Exercice 6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
6.2 Exercice 6.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
6.3 Exercice 6.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
7 Section 7 — Conditions 5
7.1 Exercice 7.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
7.2 Exercice 7.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
7.3 Exercice 7.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
7.4 Exercice 7.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
8 Section 8 — Boucles 5
8.1 Exercice 8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
8.2 Exercice 8.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
8.3 Exercice 8.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1
9 Section 9 — Listes 6
9.1 Exercice 9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
9.2 Exercice 9.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
9.3 Exercice 9.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
10 Section 10 — Tuples, sets, dict 6
10.1 Exercice 10.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
10.2 Exercice 10.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
11 Section 11 — Fonctions 7
11.1 Exercice 11.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
11.2 Exercice 11.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
11.3 Exercice 11.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
12 Section 12 — Fichiers 7
12.1 Exercice 12.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
12.2 Exercice 12.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
12.3 Exercice 12.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
13 Section 13 — Modules 8
13.1 Exercice 13.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
13.2 Exercice 13.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
14 Section 14 — Exceptions 8
14.1 Exercice 14.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
14.2 Exercice 14.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
15 Section 15 — POO 9
15.1 Exercice 15.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
15.2 Exercice 15.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
15.3 Exercice 15.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
16 Exercices de synthese 10
16.1 Exercice S1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
16.2 Exercice S2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
16.3 Exercice S3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
16.4 Exercice S4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2
1 Section 1 — Installer Python
1.1 Exercice 1.1
print("Camille")
print("J’apprends Python.")
# variante une seule ligne :
# print("Camille\nJ’apprends Python.")
2 Section 2 — Variables
2.1 Exercice 2.1
prix_ht = 100
prix_ttc = prix_ht * 1.20
print(prix_ttc)
Affiche 120.0 (type float car 1.20).
2.2 Exercice 2.2
Affichage : 5. L’instruction x = x + 2 lit la valeur actuelle de x (ici 3), lui ajoute 2, puis range
le resultat dans x : c’est une re-affectation, pas une equation mathématique.
3 Section 3 — Types
3.1 Exercice 3.1
n = 17
d = 5
print(type(n))
print(n // d)
print(n % d)
type(n) affiche <class ’int’>. Quotient 3, reste 2.
3.2 Exercice 3.2
print(int(3.9)) # 3
print(int(-3.9)) # -3
int sur un flottant tronque la partie decimale vers zero : vers l’entier immediatement plus proche
de zero.
4 Section 4 — Chaînes
4.1 Exercice 4.1
texte = " Python "
propre = [Link]().lower()
print(propre)
Affiche python.
4.2 Exercice 4.2
moy = 14.5
print(f"La moyenne est {moy:.2f}")
3
4.3 Exercice 4.3
w[1:4] designe les indices 1, 2, 3 (4 exclu) : caracteres b, c, d. Resultat : bcd.
w = "abcdef"
print(w[1:4])
5 Section 5 — Saisie au clavier
5.1 Exercice 5.1
a = int(input("Premier entier ? "))
b = int(input("Deuxieme entier ? "))
print("Somme:", a + b)
print("Produit:", a * b)
print("Premier divisible par le second ?", b != 0 and a % b == 0)
Si b == 0, la seconde partie de and n’est pas évaluée et le resultat est False.
5.2 Exercice 5.2
import math
r = float(input("Rayon ? "))
aire = [Link] * r ** 2
print(f"{aire:.3f}")
5.3 Exercice 5.3
a = int(input("Premier entier ? "))
b = int(input("Deuxieme entier ? "))
print(max(a, b))
En cas d’égalité, max(a, b) vaut simplement cette valeur commune.
6 Section 6 — Opérateurs et expressions
6.1 Exercice 6.1
(True or False) vaut True. Ensuite True and False vaut False.
print((True or False) and False)
6.2 Exercice 6.2
note = float(input("Note ? "))
print(0 <= note <= 20)
6.3 Exercice 6.3
print(bool(""))
print(bool([0]))
print(not ([] or [1]))
4
7 Section 7 — Conditions
7.1 Exercice 7.1
n = int(input("Entier ? "))
if n > 0:
print("Positif")
elif n < 0:
print("Negatif")
else:
print("Zero")
7.2 Exercice 7.2
n1 = float(input("Note 1 ? "))
n2 = float(input("Note 2 ? "))
n3 = float(input("Note 3 ? "))
moy = (n1 + n2 + n3) / 3
if moy >= 16:
print("A")
elif moy >= 12:
print("B")
elif moy >= 10:
print("C")
else:
print("Echec")
7.3 Exercice 7.3
rep = input(’Code ("oui" ou "non") ? ’)
if rep == "oui":
print("OK")
elif rep == "non":
print("Annule")
else:
print("Reponse non comprise")
7.4 Exercice 7.4
age = int(input("Age ? "))
if age >= 18:
print("Majeur")
else:
print("Mineur")
8 Section 8 — Boucles
8.1 Exercice 8.1
for k in range(1, 11):
print(f"7 x {k} = {7 * k}")
8.2 Exercice 8.2
n = int(input("n (>=1) ? "))
f = 1
for i in range(2, n + 1):
f *= i
print(f"{n}! =", f)
5
Pour n = 1, la boucle range(2, 2) est vide et f reste 1.
8.3 Exercice 8.3
somme = 0
n = int(input("Entier (0 pour finir) ? "))
while n != 0:
somme += n
n = int(input("Entier (0 pour finir) ? "))
print("Somme:", somme)
9 Section 9 — Listes
9.1 Exercice 9.1
notes = [10, 12, 8, 15]
moyenne = sum(notes) / len(notes)
print(moyenne)
Version sans sum : boucle et accumulateur.
9.2 Exercice 9.2
n = int(input("Combien de notes ? "))
tab = []
for i in range(n):
[Link](int(input(f"Entier {i+1} ? ")))
print("Moyenne:", sum(tab) / len(tab))
9.3 Exercice 9.3
vals = [3, -1, 7, 2]
meilleur = vals[0]
for x in vals[1:]:
if x > meilleur:
meilleur = x
print(meilleur)
10 Section 10 — Tuples, sets, dict
10.1 Exercice 10.1
ages = {"Alice": 20, "Bob": 22, "Chloe": 19}
for prenom, age in [Link]():
print(f"{prenom} a {age} ans")
10.2 Exercice 10.2
liste = [1, 2, 2, 3, 1, 4]
distincts = set(liste)
print(len(distincts))
Reponse : 4.
6
11 Section 11 — Fonctions
11.1 Exercice 11.1
def minimum2(a, b):
if a <= b:
return a
return b
11.2 Exercice 11.2
def est_pair(n):
return n % 2 == 0
11.3 Exercice 11.3
def somme_entiers(debut, fin):
s = 0
for k in range(debut, fin + 1):
s += k
return s
print(somme_entiers(1, 10)) # 55
12 Section 12 — Fichiers
12.1 Exercice 12.1
with open("[Link]", "w", encoding="utf-8") as f:
for i in range(1, 6):
[Link](str(i) + "\n")
somme = 0
with open("[Link]", "r", encoding="utf-8") as f:
for ligne in f:
somme += int([Link]())
print("Somme:", somme)
12.2 Exercice 12.2
with open("[Link]", "w", encoding="utf-8") as f:
[Link]("12\n")
[Link]("15\n")
[Link]("10\n")
somme = 0
n = 0
with open("[Link]", "r", encoding="utf-8") as f:
for ligne in f:
ligne = [Link]()
if ligne:
somme += int(ligne)
n += 1
print("Nombre de lignes non vides:", n)
print("Moyenne:", somme / n if n else 0)
12.3 Exercice 12.3
with open("[Link]", "w", encoding="utf-8") as f:
[Link]("nom,note\n")
7
[Link]("Alice,14\n")
[Link]("Bob,11\n")
notes = []
with open("[Link]", "r", encoding="utf-8") as f:
next(f) # ignore l’en-tete
for ligne in f:
_, note = [Link]().split(",")
[Link](int(note))
print("Moyenne:", sum(notes) / len(notes))
13 Section 13 — Modules
13.1 Exercice 13.1
import math
print(f"{[Link](2):.6f}")
13.2 Exercice 13.2
[Link] :
def carre(x):
return x * x
test_import.py :
from outils import carre
if __name__ == "__main__":
print(carre(7))
Importer seul le module (import outils) n’affiche rien car [Link] ne contient que la definition
de fonction, sans code global hors def.
14 Section 14 — Exceptions
14.1 Exercice 14.1
try:
a = int(input("Premier entier ? "))
b = int(input("Deuxieme entier ? "))
except ValueError:
print("Saisie invalide : entiers attendus.")
else:
try:
print("Quotient a/b =", a / b)
except ZeroDivisionError:
print("Division par zero impossible.")
14.2 Exercice 14.2
nom = input("Nom du fichier : ")
try:
with open(nom, "r", encoding="utf-8") as f:
n = 0
for _ in f:
n += 1
print("Nombre de lignes:", n)
except FileNotFoundError:
print("Fichier introuvable.")
8
15 Section 15 — POO
15.1 Exercice 15.1
class Rectangle:
def __init__(self, largeur, hauteur):
[Link] = largeur
[Link] = hauteur
def aire(self):
return [Link] * [Link]
def __str__(self):
return f"Rectangle {[Link]} x {[Link]}"
r = Rectangle(3, 4)
print(r, "aire =", [Link]())
15.2 Exercice 15.2
class CompteBancaire:
def __init__(self, solde_initial=0.0):
[Link] = solde_initial
def depot(self, montant):
[Link] += montant
def retrait(self, montant):
if montant > [Link]:
return False
[Link] -= montant
return True
c = CompteBancaire(100)
[Link](50)
print([Link])
print([Link](200))
print([Link](30), [Link])
15.3 Exercice 15.3
class Etudiant:
def __init__(self, nom, notes):
[Link] = nom
[Link] = list(notes)
def moyenne(self):
if not [Link]:
return 0.0
return sum([Link]) / len([Link])
def __str__(self):
return f"{[Link]}, moyenne = {[Link]():.2f}"
class Boursier(Etudiant):
def __init__(self, nom, notes, montant_bourse):
super().__init__(nom, notes)
self.montant_bourse = montant_bourse
def __str__(self):
9
return super().__str__() + f", bourse = {self.montant_bourse} EUR"
e = Etudiant("Lea", [12, 14, 11])
b = Boursier("Tom", [16, 15], 200)
print(e)
print(b)
16 Exercices de synthese
16.1 Exercice S1
ht = float(input("Prix HT ? "))
taux = float(input("TVA (pourcentage) ? "))
ttc = ht * (1 + taux / 100)
print(f"Prix TTC = {ttc:.2f}")
16.2 Exercice S2
def minimum2(a, b):
if a <= b:
return a
return b
def minimum3(a, b, c):
return minimum2(minimum2(a, b), c)
print(minimum3(5, 2, 8))
16.3 Exercice S3
n = int(input("n ? "))
tab = []
for _ in range(n):
[Link](int(input("Entier ? ")))
pairs = 0
for x in tab:
if x % 2 == 0:
pairs += 1
print("Nombre de pairs:", pairs)
16.4 Exercice S4
class CarnetAdresses:
def __init__(self):
self._data = {}
def ajouter(self, prenom, telephone):
self._data[prenom] = telephone
def trouver(self, prenom):
return self._data.get(prenom)
def lister(self):
for p, t in self._data.items():
print(f"{p} -> {t}")
if __name__ == "__main__":
c = CarnetAdresses()
[Link]("Alice", "0612345678")
10
[Link]("Bob", "0698765432")
[Link]()
print("Alice:", [Link]("Alice"))
print("Inconnu:", [Link]("Zoe"))
11