%% nav-debut : généré par gen_navigation.py, ne pas modifier à la main %%
> [!nav]
> ↩ [[Code et Développement/Programmation/Lecture de Code - Python/Lecture de code - Python|Accueil · Lecture de code - Python]]
>
> | [[Code et Développement/Programmation/Lecture de Code - Python/13_exceptions\|← Exceptions]] | [[Code et Développement/Programmation/Lecture de Code - Python/15_comprehensions\|Compréhensions →]] |
> |:---|---:|
%% nav-fin %%
# Modules et imports
Un module est un fichier Python (ou une bibliothèque) qui fournit des fonctions et constantes prêtes à l'emploi.
---
## Syntaxes d'import
```python
import math # importe le module entier
from math import sqrt, pi # importe des noms spécifiques
from math import * # importe tout (déconseillé)
import math as m # alias
```
---
## Module `math`
```python
import math
math.sqrt(16) # vaut 4.0 racine carrée (toujours un flottant)
math.floor(3.7) # vaut 3 arrondi vers le bas
math.ceil(3.2) # vaut 4 arrondi vers le haut
math.pi # vaut 3.141592653589793
math.e # vaut 2.718281828459045
math.log(100, 10) # vaut 2.0 logarithme de base 10
math.log(math.e) # vaut 1.0 logarithme naturel
math.factorial(5) # vaut 120
math.gcd(12, 8) # vaut 4 PGCD
math.isqrt(17) # vaut 4 racine entière (arrondie vers le bas)
```
---
## Module `random`
```python
import random
random.random() # float dans [0.0, 1.0[
random.randint(1, 6) # entier dans [1, 6] inclus
random.choice([1,2,3,4]) # élément aléatoire
random.shuffle(lst) # mélange la liste en place
random.sample(lst, k) # k éléments distincts sans remise
random.seed(42) # fixe la graine (résultats reproductibles)
```
---
## Module `string`
```python
import string
string.ascii_lowercase # vaut 'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase # vaut 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.digits # vaut '0123456789'
string.punctuation # vaut '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
```
---
## Module `collections`
```python
from collections import Counter, defaultdict
# Counter : comptage d'occurrences
c = Counter("abracadabra")
print(c) # affiche Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
c.most_common(2) # vaut [('a', 5), ('b', 2)]
# defaultdict : dictionnaire avec une valeur par défaut
freq = defaultdict(int)
for ch in "bonjour":
freq[ch] += 1 # une clé absente vaut d'abord int(), soit 0
print(freq["o"]) # affiche 2
```
---
## Module `sys`
```python
import sys
sys.stdin.read() # lire tout stdin d'un coup
sys.argv # arguments de la ligne de commande
sys.exit(0) # quitter le programme
```
---
## Créer son propre module
Tout fichier `.py` est un module importable.
```python
# utils.py
def carre(x):
return x * x
```
```python
# main.py
from utils import carre
print(carre(5)) # affiche 25
```
## À vous
**À manipuler :** prédisez la sortie, ligne par ligne.
```sq-affiche
import math
print(math.sqrt(25))
print(math.floor(-2.5))
print(math.ceil(7 / 2))
print(math.gcd(18, 24))
---
saisie: lignes
réponse: 5.0\n-3\n4\n6
explication: sqrt renvoie un flottant. floor arrondit vers le bas : -2.5 donne -3. 7 / 2 vaut 3.5, arrondi vers le haut à 4.
```
```sq-affiche
from collections import Counter
c = Counter("mississippi")
print(c["s"])
print(c.most_common(1))
---
saisie: lignes
réponse: 4\n[('i', 4)]
explication: i et s apparaissent 4 fois chacun. À égalité, most_common garde l'ordre de première apparition : i est vu avant s.
```
%% nav-debut : généré par gen_navigation.py, ne pas modifier à la main %%
> [!nav]
> ↩ [[Code et Développement/Programmation/Lecture de Code - Python/Lecture de code - Python|Accueil · Lecture de code - Python]]
>
> | [[Code et Développement/Programmation/Lecture de Code - Python/13_exceptions\|← Exceptions]] | [[Code et Développement/Programmation/Lecture de Code - Python/15_comprehensions\|Compréhensions →]] |
> |:---|---:|
%% nav-fin %%