Python brille par son immense bibliothèque standard : des centaines de modules prêts à l'emploi, disponibles sans installation. Au niveau Basique, vous avez survolé math, random et datetime. Ici, on approfondit ces modules et on apprend à créer les siens — une étape fondamentale pour structurer de vrais projets.
Le module math en détail
Le module math fournit les fonctions mathématiques classiques. Il doit être importé :
import mathConstantes utiles
import math
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
print(math.inf) # infini
print(math.nan) # Not a NumberFonctions essentielles
| Fonction | Effet |
|---|---|
math.sqrt(x) |
Racine carrée |
math.pow(x, y) |
x ** y (renvoie un float) |
math.exp(x) |
e ** x |
math.log(x) |
Logarithme népérien (ln) |
math.log(x, base) |
Logarithme dans la base donnée |
math.log10(x), math.log2(x) |
Log base 10 / base 2 |
math.floor(x) |
Arrondi vers le bas |
math.ceil(x) |
Arrondi vers le haut |
math.trunc(x) |
Troncature (vers zéro) |
math.fabs(x) |
Valeur absolue (float) |
math.gcd(a, b) |
PGCD (plus grand commun diviseur) |
math.factorial(n) |
n! |
import math
print("√2 =", math.sqrt(2))
print("2^10 =", math.pow(2, 10))
print("ln(e) =", math.log(math.e))
print("log10(100) =", math.log10(100))
print("floor(3.7) =", math.floor(3.7))
print("ceil(3.1) =", math.ceil(3.1))
print("7! =", math.factorial(7))Fonctions trigonométriques
| Fonction | Effet |
|---|---|
math.sin(x), math.cos(x), math.tan(x) |
Trigonométrie (en radians) |
math.asin(x), math.acos(x), math.atan(x) |
Arc-sinus, arc-cosinus, arc-tangente |
math.radians(x), math.degrees(x) |
Conversion degrés ↔ radians |
import math
angle_deg = 90
angle_rad = math.radians(angle_deg)
print(f"sin({angle_deg}°) = {math.sin(angle_rad):.4f}")
print(f"cos(π) = {math.cos(math.pi):.4f}")Le module random en détail
Pour générer des nombres aléatoires, mélanger des séquences, tirer des échantillons.
Fonctions principales
| Fonction | Effet |
|---|---|
random.random() |
Flottant entre 0.0 (inclus) et 1.0 (exclu) |
random.uniform(a, b) |
Flottant entre a et b |
random.randint(a, b) |
Entier entre a et b inclus |
random.randrange(a, b) |
Entier entre a inclus et b exclu |
random.choice(seq) |
Élément au hasard dans une séquence |
random.choices(seq, k=n) |
n éléments au hasard (avec remise) |
random.sample(seq, k=n) |
n éléments distincts (sans remise) |
random.shuffle(liste) |
Mélange la liste en place |
import random
random.seed(42) # pour reproductibilité dans la démo
print("random() :", random.random())
print("uniform(1, 10) :", random.uniform(1, 10))
print("randint(1, 6) :", random.randint(1, 6))
fruits = ["pomme", "banane", "cerise", "datte"]
print("choice :", random.choice(fruits))
print("choices (3 avec remise) :", random.choices(fruits, k=3))
print("sample (3 sans remise) :", random.sample(fruits, k=3))
# shuffle modifie EN PLACE
nombres = [1, 2, 3, 4, 5]
random.shuffle(nombres)
print("Mélangé :", nombres)Distinguer choices et sample
import random
random.seed(42)
urne = ["A", "B", "C"]
# choices : avec remise (doublons possibles)
print("choices k=5 :", random.choices(urne, k=5))
# sample : sans remise (tous distincts, max = len(urne))
print("sample k=3 :", random.sample(urne, k=3))# sample avec k > len : erreur
import random
random.sample([1, 2, 3], k=5)Le module datetime
Pour manipuler des dates et des heures. Trois classes principales :
date: une date (année, mois, jour).time: une heure (heure, minute, seconde).datetime: combinaison des deux.timedelta: une durée (pour additionner/soustraire).
Créer et afficher une date
from datetime import date, datetime
# Date à la main
jour_j = date(2025, 12, 31)
print(jour_j)
# Aujourd'hui
aujourd_hui = date.today()
print("Aujourd'hui :", aujourd_hui)
# Datetime avec heure
rdv = datetime(2025, 12, 31, 20, 30)
print(rdv)
# Maintenant
maintenant = datetime.now()
print("Maintenant :", maintenant)Arithmétique sur les dates avec timedelta
from datetime import date, timedelta
aujourd_hui = date.today()
# Durées
demain = aujourd_hui + timedelta(days=1)
dans_un_mois = aujourd_hui + timedelta(days=30)
hier = aujourd_hui - timedelta(days=1)
print("Aujourd'hui :", aujourd_hui)
print("Demain :", demain)
print("Dans un mois :", dans_un_mois)
print("Hier :", hier)
# Différence entre deux dates → timedelta
anniversaire = date(2025, 12, 25)
noel_prochain_delta = anniversaire - aujourd_hui
print(f"Jours jusqu'au 25 décembre : {noel_prochain_delta.days}")Formater une date : strftime
La méthode strftime (string format time) convertit une date en chaîne selon un format :
| Code | Sens |
|---|---|
%Y |
Année sur 4 chiffres (2025) |
%y |
Année sur 2 chiffres (25) |
%m |
Mois sur 2 chiffres (01-12) |
%d |
Jour du mois sur 2 chiffres (01-31) |
%H, %M, %S |
Heure, minute, seconde |
%A, %a |
Jour de la semaine (long / court) |
%B, %b |
Mois (long / court) |
from datetime import datetime
maintenant = datetime(2025, 12, 31, 14, 30, 0)
print(maintenant.strftime("%d/%m/%Y")) # 31/12/2025
print(maintenant.strftime("%d %B %Y")) # 31 December 2025
print(maintenant.strftime("%Y-%m-%d %H:%M:%S")) # 2025-12-31 14:30:00
print(maintenant.strftime("%A")) # WednesdayConvertir une chaîne en date : strptime
Inverse de strftime : parser une chaîne pour en extraire une date.
from datetime import datetime
saisie = "31/12/2025"
dte = datetime.strptime(saisie, "%d/%m/%Y")
print(dte)
print(type(dte))Le format doit correspondre exactement à la chaîne, sinon ValueError.
from datetime import datetime
datetime.strptime("31-12-2025", "%d/%m/%Y") # mauvais séparateur