python_guide/python.md
2023-12-14 14:49:05 +01:00

135 lines
2.8 KiB
Markdown

# Python
Hésite pas à regarder des repos existants sur GitHub. Ce n'est pas de la triche
si tu t'inspires de leur algo tant que tu ne copies pas le code.
## man en python
Tu peux lancer un shell dans un terminal en lançant `python` dans ton terminal
De la, `help(ord)` pour avoir le man de `ord` et `exit()` pour quitter.
```bash
$ python
>>> help(ord)
>>> exit()
```
Si tu veux le man de math.ceil, il faut d'abord importer math
```bash
$ python
>>> import math
>>> help(math.ceil)
>>> exit()
```
Tu as des mans pour tous les types aussi pour savoir ce que tu peux faire
avec : `help(int)`, `help(list)`, `help(str)`. Toutes les fonctions
`__something__` sont des fonction spéciales. Par ex, `__add__` gère le
comportement si tu fais un `+` (`"abc" + "def" == "abcdef"`), c'est pas hyper
important si tu comprends pas cette partie pour l'instant. Par contre
`"abc".endswith()` ou `["a", "b"].append()` pourraient t'être utiles.
## Condition
```python
if cond and cond2 or cond3:
print(hello)
```
## Printf mais mieux
```python
a = 2
b = 2.45675325
s = "hello"
print(f"a = {a}, b = {b:.2f}, s = {s}") # affiche "a = 2, b = 2.45, s = hello"
```
`f""` (on appelle ça une fstring) te permet d'insérer une variable `{var}` dans ta
string. Comme en C, tu peux appliquer des modificateurs sur cette variable
`{var:mod}`. La syntaxe de mod est très proche de celle du C :
```c
// c
#include <stdio.h>
float b = 2.45675325;
printf("%.2f", b);
```
```python
# python
float b = 2.45675325
print(f"{b:.2f}")
```
## For
1. for (int i = 0; i < 3; i++)
```python
for i in range(3):
print(i) # affiche 0, 1, 2
```
2. for (int i = 0; s[i] != '\0'; i++)
```python
s = "abc"
for c in s:
print(c) # affiche "a\nb\nc\n"
```
2. un mixe des deux
```python
l = ["abc", "def", "ghi"]
for (i, nb) in enumerate(l):
print(i, nb) # affiche "0 abc\n1 def\n2 ghi"
```
Pour chaque tour de boucle, `enumerate` te donne deux variables : l'index et
la valeur (`i` et `str[i]`)
## Tableaux
La syntaxe est un peu bizarre, mais elle permet d'initialiser le tableau avec
ce que tu veux.<br>
Dans tous les exemples, `tab == tab1`.
```python
tab = [[0 for x in range(2)] for y in range(3)]
tab1 = [
[0, 0]
[0, 0]
[0, 0]
]
```
Pas de gestion de la ram en python, donc 2 et 3 peuvent être des variables.
... ou des strings
```python
s = "abc"
tab = [[0 for x in s] for y in range(2)]
tab1 = [
[0, 0, 0]
[0, 0, 0]
]
```
```python
tab = [[x for x in "abc"] for y in range(2)]
tab1 = [
["a", "b", "c"]
["a", "b", "c"]
]
```
Tu peux aussi modifier la taille de ton tableau après coup avec `tab.append()`
et `tab.pop()`.
## Conversions
```python
a = int("2") # a = 2
b = str(a) # b = "2"
```
## Gestion d'erreur
```python
try:
a = int("z")
except:
a = 0
```
Si `"z"` n'est pas un `int` valide, le code dans `except` sera exécuté.