2.8 KiB
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.
$ python
>>> help(ord)
>>> exit()
Si tu veux le man de math.ceil, il faut d'abord importer math
$ 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
if cond and cond2 or cond3:
print(hello)
Printf mais mieux
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
#include <stdio.h>
float b = 2.45675325;
printf("%.2f", b);
# python
float b = 2.45675325
print(f"{b:.2f}")
For
- for (int i = 0; i < 3; i++)
for i in range(3):
print(i) # affiche 0, 1, 2
- for (int i = 0; s[i] != '\0'; i++)
s = "abc"
for c in s:
print(c) # affiche "a\nb\nc\n"
- un mixe des deux
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.
Dans tous les exemples, tab == tab1
.
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
s = "abc"
tab = [[0 for x in s] for y in range(2)]
tab1 = [
[0, 0, 0]
[0, 0, 0]
]
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
a = int("2") # a = 2
b = str(a) # b = "2"
Gestion d'erreur
try:
a = int("z")
except:
a = 0
Si "z"
n'est pas un int
valide, le code dans except
sera exécuté.