Aide-mémoire
1. Variables, types et opérations
Section intitulée « 1. Variables, types et opérations »Types de base
Section intitulée « Types de base »| Type | Description | Exemple |
|---|---|---|
int | Nombre entier | 42, -7, 0 |
float | Nombre à virgule | 3.14, -0.5 |
str | Chaîne de caractères | "Bonjour", 'A' |
bool | Booléen | True, False |
Conversions
Section intitulée « Conversions »int("42") # str → intfloat("3.14") # str → floatstr(42) # int → strint(3.99) # float → int (tronque, ne pas confondre avec round)Opérateurs arithmétiques
Section intitulée « Opérateurs arithmétiques »| Opérateur | Description | Exemple | Résultat |
|---|---|---|---|
+ - * | Addition, soustraction, multiplication | 7 * 3 | 21 |
/ | Division réelle | 7 / 2 | 3.5 |
// | Division entière | 7 // 2 | 3 |
% | Modulo (reste) | 7 % 2 | 1 |
** | Puissance | 2 ** 3 | 8 |
Opérateurs d’affectation composés
Section intitulée « Opérateurs d’affectation composés »x += 3 # x = x + 3x -= 1 # x = x - 1x *= 2 # x = x * 2x /= 4 # x = x / 42. Entrée et sortie
Section intitulée « 2. Entrée et sortie »# Sortieprint("Bonjour", nom, "! Tu as", age, "ans.")
# Entrée — toujours une chaînereponse = input("Ton nom? ")age = int(input("Ton âge? "))
inputretourne toujours un string (str)!
3. Conditions
Section intitulée « 3. Conditions »Avec if-elif-else
Section intitulée « Avec if-elif-else »if condition: instructionselif autre_condition: instructionselse: instructionsAvec match
Section intitulée « Avec match »match variable: case valeur1: instructions case valeur2: instructions case _: instructions_par_defautOpérateurs de comparaison
Section intitulée « Opérateurs de comparaison »| Opérateur | Signification |
|---|---|
== != | Égal / Différent |
< > <= >= | Comparaisons numériques |
Opérateurs logiques
Section intitulée « Opérateurs logiques »| Opérateur | Signification |
|---|---|
and | Les deux doivent être vraies |
or | Au moins une doit être vraie |
not | Inverse le booléen |
4. Boucles
Section intitulée « 4. Boucles »while — répéter tant qu’une condition est vraie
Section intitulée « while — répéter tant qu’une condition est vraie »compteur = 0while compteur < 5: print(compteur) compteur = compteur + 1for — parcourir une séquence
Section intitulée « for — parcourir une séquence »# Avec rangefor i in range(5): # 0, 1, 2, 3, 4 print(i)
for i in range(2, 8): # 2, 3, 4, 5, 6, 7 print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8 print(i)
# Parcourir une listefor fruit in fruits: print(fruit)
# Avec indicefor i in range(len(fruits)): print(i, fruits[i])Contrôle de boucle
Section intitulée « Contrôle de boucle »| Mot-clé | Effet |
|---|---|
break | Sort immédiatement de la boucle |
continue | Saute à l’itération suivante |
5. Fonctions intégrées et modules
Section intitulée « 5. Fonctions intégrées et modules »Fonctions globales essentielles
Section intitulée « Fonctions globales essentielles »| Fonction | Description |
|---|---|
print() | Afficher (ne retourne rien) |
input() | Saisie utilisateur (retourne str) |
int(), float(), str(), bool() | Conversion de type |
len() | Longueur (liste, chaîne, dict) |
round(x, n) | Arrondir à n décimales |
format(x, spec) | Formater un nombre en chaîne |
abs(), max(), min(), sum() | Opérations numériques |
range() | Séquence d’entiers |
type() | Connaître le type d’une valeur |
Modules courants
Section intitulée « Modules courants »import math # math.sqrt(), math.pi, math.ceil()import random # random.randint(), random.choice()6. Créer ses propres fonctions
Section intitulée « 6. Créer ses propres fonctions »def nom_fonction(param1, param2): instructions return resultatParamètres optionnels
Section intitulée « Paramètres optionnels »def saluer(nom, langue="fr"): if langue == "fr": print("Bonjour " + nom) else: print("Hello " + nom)
saluer("Alice") # langue="fr" par défautsaluer("Bob", "en") # langue="en"Portée des variables
Section intitulée « Portée des variables »x = 10 # Variable globale
def modifier(): x = 20 # Variable LOCALE (nouvelle, pas la globale) return x
print(modifier()) # 20print(x) # 10 — la globale n'a pas changéBonnes pratiques
Section intitulée « Bonnes pratiques »| Principe | Explication |
|---|---|
| Une seule tâche | Chaque fonction fait une chose |
| Autonome | Ne dépend pas de variables globales (sauf constantes) |
return plutôt que print | Retourner le résultat, pas l’afficher |
| Paramètres explicites | Tout ce dont elle a besoin est passé en paramètre |
| Nom descriptif | calculer_imc plutôt que f1 |
7. Les listes
Section intitulée « 7. Les listes »Création et manipulation
Section intitulée « Création et manipulation »notes = [72, 85, 91, 68]vide = []
notes.append(77) # Ajouter à la finnotes.insert(0, 95) # Insérer à la position 0notes.pop(2) # Retirer l'élément à l'indice 2notes.remove(68) # Retirer la première occurrence de 68notes.sort() # Trier en place (retourne None!)notes.reverse() # Inverser en placeIndexation et tranchage
Section intitulée « Indexation et tranchage »notes[0] # Premier élémentnotes[-1] # Dernier élémentnotes[1:4] # Éléments d'indice 1, 2, 3notes[:3] # Les 3 premiersnotes[2:] # À partir de l'indice 2notes[::-1] # Copie inverséeParcours
Section intitulée « Parcours »# Par valeurfor note in notes: print(note)
# Par indicefor i in range(len(notes)): print(i, notes[i])8. Dictionnaires
Section intitulée « 8. Dictionnaires »Création et accès
Section intitulée « Création et accès »etudiant = {"nom": "Tremblay", "note": 85, "groupe": "A"}
etudiant["nom"] # "Tremblay"etudiant["age"] # ❌ KeyErroretudiant.get("age", 0) # 0 (valeur par défaut)etudiant["age"] = 20 # Ajout d'une cléetudiant["note"] = 90 # ModificationParcours
Section intitulée « Parcours »for cle in etudiant: # Clés seulement print(cle)
for cle, valeur in etudiant.items(): # Clés et valeurs print(cle, ":", valeur)9. Ensembles
Section intitulée « 9. Ensembles »voyelles = {"a", "e", "i", "o", "u"}vide = set()| Opération | Syntaxe | Description |
|---|---|---|
| Union | a | b | Tous les éléments |
| Intersection | a & b | Éléments communs |
| Différence | a - b | Dans a mais pas dans b |
| Différence symétrique | a ^ b | Dans l’un ou l’autre, pas les deux |
| Appartenance | x in a | Très rapide (contrairement aux listes) |
10. Listes imbriquées et matrices
Section intitulée « 10. Listes imbriquées et matrices »matrice = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrice[1][2] # 6 (ligne 1, colonne 2)len(matrice) # 3 (nombre de lignes)len(matrice[0]) # 3 (nombre de colonnes)11. Chaînes de caractères
Section intitulée « 11. Chaînes de caractères »Méthodes courantes
Section intitulée « Méthodes courantes »| Méthode | Description | Exemple |
|---|---|---|
.upper() / .lower() | Majuscules / minuscules | "Abc".upper() → "ABC" |
.strip() | Enlever les espaces aux extrémités | " hi ".strip() → "hi" |
.split(sep) | Découper en liste | "a,b,c".split(",") → ["a","b","c"] |
.replace(a, b) | Remplacer | "abc".replace("b", "X") → "aXc" |
.find(s) | Position (ou -1) | "hello".find("ll") → 2 |
.count(s) | Nombre d’occurrences | "abba".count("b") → 2 |
.startswith(s) | Commence par? | "Bonjour".startswith("Bon") → True |
.isdigit() | Que des chiffres? | "42".isdigit() → True |
Indexation
Section intitulée « Indexation »Les chaînes se comportent comme des listes en lecture seule :
mot = "Python"mot[0] # "P"mot[-1] # "n"mot[2:5] # "tho"
for lettre in mot: print(lettre)12. NumPy
Section intitulée « 12. NumPy »Création de tableaux
Section intitulée « Création de tableaux »import numpy as np
a = np.array([1, 2, 3, 4]) # 1Dm = np.array([[1, 2], [3, 4]]) # 2Dz = np.zeros((3, 4)) # Matrice 3×4 de zérosPropriétés
Section intitulée « Propriétés »m.shape # (2, 2) — dimensionsm.dtype # dtype('int64') — type des élémentsm.ndim # 2 — nombre de dimensionsOpérations vectorisées
Section intitulée « Opérations vectorisées »a = np.array([10, 20, 30])a * 2 # array([20, 40, 60])a + 5 # array([15, 25, 35])a > 15 # array([False, True, True]) — masque booléena[a > 15] # array([20, 30]) — filtrageStatistiques avec axis
Section intitulée « Statistiques avec axis »m = np.array([[1, 2, 3], [4, 5, 6]])
np.sum(m) # 21 (tout)np.sum(m, axis=0) # array([5, 7, 9]) — par colonnenp.sum(m, axis=1) # array([6, 15]) — par ligne
np.mean(m, axis=0) # Moyenne par colonnenp.std(m, axis=1) # Écart-type par lignenp.argmax(m, axis=1) # Indice du max par ligne13. Fichiers
Section intitulée « 13. Fichiers »with open("donnees.csv", "r", encoding="utf-8") as fichier: contenu = fichier.read() # Tout en une chaîne # ou lignes = fichier.readlines() # Liste de lignesModule CSV
Section intitulée « Module CSV »import csv
# csv.reader — accès par positionwith open("donnees.csv", "r") as fichier: lecteur = csv.reader(fichier) en_tete = next(lecteur) # Sauter l'en-tête for rangee in lecteur: print(rangee[0], rangee[1]) # Toujours des str!
# csv.DictReader — accès par nomwith open("donnees.csv", "r") as fichier: lecteur = csv.DictReader(fichier) for rangee in lecteur: print(rangee["produit"])Écriture
Section intitulée « Écriture »with open("resultats.txt", "w") as fichier: fichier.write("Ligne 1\n") # \n obligatoire
import csvwith open("export.csv", "w", newline="") as fichier: ecrivain = csv.writer(fichier) ecrivain.writerow(["col1", "col2"])14. Gestion d’erreurs : try-except
Section intitulée « 14. Gestion d’erreurs : try-except »try: code_risqueexcept TypeError: traitement_erreur_typeexcept ValueError: traitement_erreur_valeurErreurs courantes
Section intitulée « Erreurs courantes »| Erreur | Cause typique |
|---|---|
ValueError | int("abc") — conversion impossible |
IndexError | liste[10] — index hors limites |
KeyError | dict["absent"] — clé inexistante |
TypeError | "5" + 3 — types incompatibles |
ZeroDivisionError | 10 / 0 |
FileNotFoundError | open("inexistant.csv") |
Récupérer le message
Section intitulée « Récupérer le message »try: x = int("abc")except ValueError as e: print("Erreur : " + str(e))