Software Engineering">
Cours Python
Cours Python
Python — La
Référence Complète
Cours intensif — Semestre | 3ème Année Licence TI
• Créé en 1991 par Guido van Rossum (hommage aux Monty Python)
• Interprété, haut niveau, typage dynamique fort
• Multi-paradigme : impératif, objet, fonctionnel
• Domaines d'application :
• → Data Science & IA (NumPy, Pandas, TensorFlow, PyTorch)
• → Web (Django, Flask, FastAPI)
• → Automatisation & Scripting
• → Cybersécurité & Hacking éthique
• Classé régulièrement #1 par TIOBE et Stackoverflow Survey
• PyPI : +500 000 packages disponibles via pip
Chapitre 1 — Environnement Python
# Fichier [Link]
def main():
prenom = input('Votre prénom: ')
print(f'Bonjour {prenom} !')
if __name__ == '__main__':
main()
💡 Le bloc if __name__ == '__main__' permet d'exécuter le code seulement quand le fichier est lancé directement (pas
importé).
Chapitre 2 — Types Scalaires
etudiant = {
'nom': 'Ben Ali', 'prenom': 'Mohamed',
'moyenne': 14.5, 'filiere': 'TI'
}
# Accès sécurisé
print([Link]('age', 20)) # 20 (valeur par défaut)
# Itération
for cle, val in [Link]():
print(f'{cle:10}: {val}')
# Compréhension de dictionnaire
notes = {'Ali': 15, 'Sana': 18, 'Omar': 11}
mentions = {n: 'Admis' if v>=10 else 'Ajourné'
for n, v in [Link]()}
💡 Les dictionnaires sont la structure la plus utilisée en Python pour les données structurées.
Chapitre 3 — Conditions
note = 14
if note >= 16: mention = 'Très Bien'
elif note >= 14: mention = 'Bien'
elif note >= 12: mention = 'Assez Bien'
elif note >= 10: mention = 'Passable'
else: mention = 'Ajourné'
# Expression ternaire
statut = 'Admis' if note >= 10 else 'Ajourné'
# for + range()
for i in range(1, 6): # 1,2,3,4,5
print(i, end=' ')
# Carrés de 0 à 9
carres = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Transformation
noms = ['alice','bob','charlie']
majuscules = [[Link]() for n in noms]
# Dict comprehension
notes = {'Ali':15,'Sana':18,'Omar':11}
admis = {n:v for n,v in [Link]() if v>=10}
# Set comprehension
consonnes = {c for c in 'Python' if c not in 'aeiouAEIOU'}
💡 Les compréhensions sont plus rapides et plus Pythoniques que les boucles traditionnelles.
Chapitre 4 — Fonctions
# Appels variés
print(calculer_moyenne(15, 18, 12)) # 15.0
print(calculer_moyenne(15, 18, arrondi=1)) # 16.5
💡 Toujours écrire une docstring pour documenter vos fonctions (format Google ou NumPy).
Chapitre 4 — Décorateurs
def chronometre(f):
@[Link](f) # préserve les métadonnées
def wrapper(*args, **kwargs):
t0 = time.perf_counter()
result = f(*args, **kwargs)
t1 = time.perf_counter()
print(f'[{f.__name__}] {t1-t0:.4f}s')
return result
return wrapper
@chronometre
def fibonacci(n):
a, b = 0, 1
for _ in range(n): a, b = b, a+b
return a
Programmation
Orientée Objet
Chapitres 5 à 7 · Classes · Héritage · Dunder Methods
Chapitre 5 — Concepts POO
class Etudiant:
etablissement = 'ISET Jendouba' # attribut de classe
compteur = 0
def moyenne(self):
return sum([Link])/len([Link]) if [Link] else 0
e = Etudiant('Ben Ali','Mohamed','12345')
e.ajouter_note(15); e.ajouter_note(18)
💡 self est la référence à l'objet
print(f'Moyenne: courant. Tous les paramètres
{[Link]():.2f}') self doivent
# Moyenne: être explicitement déclarés.
16.50
Chapitre 6 — Encapsulation & @property
class CompteBancaire:
def __init__(self, titulaire, solde=0):
[Link] = titulaire
self.__solde = solde # attribut privé (name mangling)
@property
def solde(self): # getter
return self.__solde
@[Link]
def solde(self, v): # setter avec validation
if v < 0: raise ValueError('Solde négatif interdit')
self.__solde = v
c = CompteBancaire('Ali', 1000)
[Link](500) # Dépôt +500 DT → Solde: 1500 DT
💡 public, _protégé (convention),
print([Link]) # 1500__privé
(via(name mangling → _Classe__attribut)
getter)
Chapitre 6 — Héritage & Polymorphisme
class Forme:
def aire(self): raise NotImplementedError
def perimetre(self): raise NotImplementedError
class Rectangle(Forme):
def __init__(self, l, h):
self.l, self.h = l, h
def aire(self): return self.l * self.h
def perimetre(self): return 2*(self.l+self.h)
class Cercle(Forme):
import math
def __init__(self, r): self.r = r
def aire(self): return [Link] * self.r**2
def perimetre(self): return 2*[Link]*self.r
class Fraction:
def __init__(self, n, d):
from math import gcd
g = gcd(abs(n), abs(d))
self.n, self.d = n//g, d//g
a = Fraction(1,2); b = Fraction(1,3)
print(a + b) # 5/6
💡 Les méthodes
print(a * b)dunder# permettent
1/6 l'intégration naturelle avec la syntaxe Python.
PARTIE III
# Exception personnalisée
class NoteInvalideError(ValueError):
def __init__(self, note):
super().__init__(f'Note {note} hors de [0,20]')
[Link] = note
def valider(note):
if not 0 <= note <= 20: raise NoteInvalideError(note)
💡 Le bloc finally est
return toujours exécuté — idéal pour libérer des ressources.
note
Chapitre 8 — Fichiers JSON & CSV
# JSON — écriture
data = [{'nom':'Ali','note':15},{'nom':'Sana','note':18}]
with open('[Link]','w',encoding='utf-8') as f:
[Link](data, f, ensure_ascii=False, indent=2)
# JSON — lecture
with open('[Link]','r',encoding='utf-8') as f:
loaded = [Link](f)
# CSV — lecture
with open('[Link]','r',encoding='utf-8') as f:
rows = list([Link](f))
💡 Toujours utiliser 'with open()' — fermeture automatique même en cas d'erreur.
Chapitre 9 — Modules os, datetime, math
# os
print([Link]())
[Link]('data/2025', exist_ok=True)
fichiers = [Link]('.')
# datetime
now = [Link]()
print([Link]('%d/%m/%Y %H:%M')) # 15/01/2025 14:30
naissance = date(2003, 5, 20)
age = ([Link]() - naissance).days // 365
echeance = [Link]() + timedelta(days=30)
# math
print([Link](144)) # 12.0
print([Link](10)) # 3628800
print([Link](48, 18)) # 6
print(math.log2(1024)) # 10.0
Chapitre 10 — NumPy Essentiels
import numpy as np
# Création
notes = [Link]([15, 18, 12, 17, 9, 14])
zeros = [Link]((3, 4))
oeil = [Link](3) # matrice identité
seq = [Link](0,10,2) # [0 2 4 6 8]
# Algèbre linéaire
A = [Link]([[1,2],[3,4]])
B = [Link]([[5,6],[7,8]])
print(A @ B) # produit matriciel
print([Link](A)) # -2.0 (déterminant)
💡 NumPy est 10 à 100x plus rapide que les listes Python pour les calculs numériques.
Chapitre 10 — Pandas DataFrame
import pandas as pd
df = [Link]({
'Nom': ['Ali','Sana','Omar','Ines'],
'Filiere':['TI','SI','TI','RS'],
'Moyenne':[14.5, 17.8, 11.2, 15.0]
})
# Exploration
[Link](); [Link]()
# Nouvelles colonnes
df['Mention'] = df['Moyenne'].apply(
lambda m: 'TB' if m>=16 else 'B' if m>=14 else 'P')
# Groupement
💡 Pandas = Excel pour Python ! Lecture CSV, XLSX, SQL, JSON, API REST...
print([Link]('Filiere')['Moyenne'].agg(['mean','max']))
df.to_csv('[Link]', index=False)
PARTIE IV
Travaux Pratiques
2h 3h
3h 4h
TP 2 — Bibliothèque (Architecture POO)
class Livre:
def __init__(self, isbn, titre, auteur, annee):
[Link] = isbn; [Link] = titre
[Link] = auteur; [Link] = True
def __str__(self):
s = '✓' if [Link] else '✗'
return f'[{s}] {[Link]} — {[Link]}'
class Emprunt:
DUREE = 14 # jours
def __init__(self, livre, membre):
[Link] = livre; [Link] = membre
[Link] = [Link]()
[Link] = [Link] + timedelta(days=[Link])
def en_retard(self):
return [Link]() > [Link]
@[Link]('/api/livres', methods=['GET'])
def get_livres():
dispo = [Link]('disponible')
if dispo: return jsonify([l for l in LIVRES if l['dispo']])
return jsonify(LIVRES)
@[Link]('/api/livres', methods=['POST'])
def create_livre():
data = request.get_json()
if not all(k in data for k in ['isbn','titre','auteur']):
abort(400, 'Champs manquants')
[Link]({**data, 'disponible': True})
return jsonify(data), 201
@[Link](404)
def not_found(e): return jsonify(error=str(e)), 404