aidememo:aide_memoire
Différences
Ci-dessous, les différences entre deux révisions de la page.
aidememo:aide_memoire [2018/07/31 09:18] – créée ronan | aidememo:aide_memoire [2019/01/11 15:14] (Version actuelle) – rguyader | ||
---|---|---|---|
Ligne 16: | Ligne 16: | ||
* Ordre de recherche / champs des variables : look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names | * Ordre de recherche / champs des variables : look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names | ||
* Une fonction copie les arguments en variables locales, sauf les listes. Cependant, les arguments par défaut ne sont évalués qu'une seule fois (=> liste par défaut persistante). Si l'on veut éviter ce comportement, | * Une fonction copie les arguments en variables locales, sauf les listes. Cependant, les arguments par défaut ne sont évalués qu'une seule fois (=> liste par défaut persistante). Si l'on veut éviter ce comportement, | ||
- | + | <code python> | |
- | def f(a, L=None): | + | def f(a, L=None): |
- | if L is None: | + | if L is None: |
- | L = [] | + | L = [] |
- | L.append(a) | + | L.append(a) |
- | return L | + | return L |
+ | </ | ||
===== Quoting : ===== | ===== Quoting : ===== | ||
* Double quote > simple quote | * Double quote > simple quote | ||
* Sur lignes multiples (docstrings) : | * Sur lignes multiples (docstrings) : | ||
- | + | <code python> | |
- | """ | + | """ |
- | sur | + | sur |
- | plusieurs | + | plusieurs |
- | lignes """ | + | lignes """ |
+ | </ | ||
* Unlike other languages, special characters such as \n have the same meaning with both single (' | * Unlike other languages, special characters such as \n have the same meaning with both single (' | ||
Ligne 46: | Ligne 46: | ||
* Fin de ligne : print(b, end=',' | * Fin de ligne : print(b, end=',' | ||
* Un caractère peut être utilisé pour joindre des chaines : | * Un caractère peut être utilisé pour joindre des chaines : | ||
+ | <code python> | ||
+ | def concat(*args, | ||
+ | return sep.join(args) | ||
- | def concat(*args, | + | concat(" |
- | return sep.join(args) | + | concat(" |
- | + | </ | |
- | | + | |
- | concat(" | + | |
* strip : virer les espaces à la fin | * strip : virer les espaces à la fin | ||
+ | <code python> | ||
'tea for too' | 'tea for too' | ||
+ | </ | ||
===== Variables : ===== | ===== Variables : ===== | ||
* Les chaines ne peuvent pas être modifiées | * Les chaines ne peuvent pas être modifiées | ||
* L' | * L' | ||
- | + | <code python> | |
- | a, b = 0, 1 | + | a, b = 0, 1 |
- | a, b = b, a+b | + | a, b = b, a+b |
+ | </ | ||
===== Boucles de contrôle : ===== | ===== Boucles de contrôle : ===== | ||
==== while ==== | ==== while ==== | ||
- | + | <code python> | |
- | a, b = 0, 1 | + | a, b = 0, 1 |
- | while b < 10: | + | while b < 10: |
- | print(b) | + | print(b) |
- | a, b = b, a+b | + | a, b = b, a+b |
- | + | ||
- | while True: (utiliser ensuite return True/False dans les tests) | + | |
| | ||
+ | while True: (utiliser ensuite return True/False dans les tests) | ||
+ | </ | ||
==== if ==== | ==== if ==== | ||
- | + | <code python> | |
- | if x < 0: | + | if x < 0: |
- | x = 0 | + | x = 0 |
- | print(' | + | print(' |
- | elif x == 0: | + | elif x == 0: |
- | print(' | + | print(' |
- | elif x == 1: | + | elif x == 1: |
- | print(' | + | print(' |
- | else: | + | else: |
- | print(' | + | print(' |
+ | </ | ||
==== for ==== | ==== for ==== | ||
- | + | <code python> | |
- | words = [' | + | words = [' |
- | for w in words: | + | for w in words: |
- | print(w, len(w)) | + | print(w, len(w)) |
- | for w in words[: | + | for w in words[: |
- | if len(w) > 6: | + | if len(w) > 6: |
- | words.insert(0, | + | words.insert(0, |
+ | </ | ||
==== for/else ==== | ==== for/else ==== | ||
- | + | <code ptyhon> | |
- | # else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs | + | # else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs |
- | # nombres premiers de 2 à 10 | + | # nombres premiers de 2 à 10 |
- | for n in range(2, 10): | + | for n in range(2, 10): |
- | for x in range(2, n): | + | for x in range(2, n): |
- | if n % x == 0: | + | if n % x == 0: |
- | print(n, ' | + | print(n, ' |
- | break | + | break |
- | else: | + | else: |
- | #loop fell through without finding a factor | + | #loop fell through without finding a factor |
- | print(n, 'is a prime number' | + | print(n, 'is a prime number' |
+ | </ | ||
==== for/ | ==== for/ | ||
- | + | <code python> | |
- | # | + | continue force to continue next for iteration |
- | for num in range(2, 10): | + | for num in range(2, 10): |
- | if num % 2 == 0: | + | if num % 2 == 0: |
- | print(" | + | print(" |
- | continue | + | continue |
- | print(" | + | print(" |
+ | </ | ||
==== pass ==== | ==== pass ==== | ||
Ne sert à rien sauf à meubler syntaxiquement | Ne sert à rien sauf à meubler syntaxiquement | ||
- | + | <code python> | |
- | while True: | + | while True: |
- | pass # Busy-wait for keyboard interrupt (Ctrl+C) | + | pass # Busy-wait for keyboard interrupt (Ctrl+C) |
- | class MyEmptyClass: | + | class MyEmptyClass: |
- | pass | + | pass |
- | def initlog(*args): | + | def initlog(*args): |
- | pass # Remember to implement this! | + | pass # Remember to implement this! |
+ | </ | ||
===== Itérateurs ===== | ===== Itérateurs ===== | ||
+ | <code python> | ||
+ | range | ||
+ | range(5) | ||
+ | range(5, 10) # 5 through 9 | ||
+ | range(0, 10, 3) # 0, 3, 6, 9 | ||
+ | range(-10, -100, -30) # -10, -40, -70 | ||
- | range | + | list(range(5)) # donne [0, 1, 2, 3, 4] |
- | range(5) | + | </ |
- | range(5, 10) # 5 through 9 | + | |
- | range(0, 10, 3) # 0, 3, 6, 9 | + | |
- | range(-10, -100, -30) # -10, -40, -70 | + | |
- | + | ||
- | | + | |
===== Structures de données ===== | ===== Structures de données ===== | ||
Ligne 163: | Ligne 163: | ||
* length : len(< | * length : len(< | ||
* replace/ | * replace/ | ||
+ | <code python> | ||
letters = [' | letters = [' | ||
letters[2: | letters[2: | ||
letters[2: | letters[2: | ||
letters[:] = [] | letters[:] = [] | ||
+ | </ | ||
* nesting possible (lists of lists), making multidimansional array : x[0][1] | * nesting possible (lists of lists), making multidimansional array : x[0][1] | ||
* test de présence dans liste : in ; exemple : if < | * test de présence dans liste : in ; exemple : if < | ||
==== Tuples ==== | ==== Tuples ==== | ||
+ | <code python> | ||
*name | *name | ||
unpack : | unpack : | ||
Ligne 179: | Ligne 179: | ||
list(range(*args)) | list(range(*args)) | ||
[3, 4, 5] | [3, 4, 5] | ||
+ | </ | ||
==== Dictionnaires ==== | ==== Dictionnaires ==== | ||
- | + | <code python> | |
- | name | + | name |
- | keys = sorted(name.keys()) | + | keys = sorted(name.keys()) |
- | for kw in keys: | + | for kw in keys: |
- | print(kw, ":", | + | print(kw, ":", |
+ | </ | ||
**RQ :** si pas trié, alors l' | **RQ :** si pas trié, alors l' | ||
- | + | <code python> | |
- | unpack : | + | unpack : |
- | d = {" | + | d = {" |
- | function(**d) | + | function(**d) |
+ | </ | ||
==== Fonctions ==== | ==== Fonctions ==== | ||
- | + | <code python> | |
- | def fib2(n): | + | def fib2(n): |
- | """ | + | """ |
- | result = [] | + | result = [] |
- | a, b = 0, 1 | + | a, b = 0, 1 |
- | while a < n: | + | while a < n: |
- | result.append(a) | + | result.append(a) |
- | a, b = b, a+b | + | a, b = b, a+b |
return result | return result | ||
- | | + | f100 = fib2(100) |
- | f100 # write the result | + | f100 # write the result |
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] | # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] | ||
+ | </ | ||
**Rq documentation :** La ligne de commentaire doit décrire de manière succincte le but de la fonction. Commencer par une majuscule et finir par un point. Si plus de ligne, laisser une vide. | **Rq documentation :** La ligne de commentaire doit décrire de manière succincte le but de la fonction. Commencer par une majuscule et finir par un point. Si plus de ligne, laisser une vide. | ||
+ | <code python> | ||
def my_function(): | def my_function(): | ||
""" | """ | ||
Ligne 217: | Ligne 218: | ||
pass | pass | ||
print(my_function.__doc__) | print(my_function.__doc__) | ||
+ | </ | ||
**Fonctions avec nombre d' | **Fonctions avec nombre d' | ||
Ligne 231: | Ligne 233: | ||
| | ||
**fonctions anonymes : lambda** | **fonctions anonymes : lambda** | ||
+ | |||
+ | <code python> | ||
def make_incrementor(n): | def make_incrementor(n): | ||
return lambda x: x + n | return lambda x: x + n | ||
Ligne 240: | Ligne 244: | ||
pairs.sort(key=lambda pair: pair[1]) | pairs.sort(key=lambda pair: pair[1]) | ||
pairs # [(4, ' | pairs # [(4, ' | ||
+ | </ | ||
* lambda : facilité de visualisation, | * lambda : facilité de visualisation, | ||
Ligne 252: | Ligne 257: | ||
On peut réagir à plusieurs exceptions en même temps : except (RuntimeError, | On peut réagir à plusieurs exceptions en même temps : except (RuntimeError, | ||
+ | <code python> | ||
try: | try: | ||
f = open(' | f = open(' | ||
Ligne 267: | Ligne 273: | ||
finally: | finally: | ||
print(' | print(' | ||
+ | </ | ||
On peut lever soi-même des exceptions : | On peut lever soi-même des exceptions : | ||
+ | <code python> | ||
raise NameError(' | raise NameError(' | ||
+ | </ | ||
===== Coder proprement ===== | ===== Coder proprement ===== | ||
Ligne 302: | Ligne 311: | ||
* **attention :** pour 1 et 2 éléments : | * **attention :** pour 1 et 2 éléments : | ||
+ | <code python> | ||
empty = () | empty = () | ||
singleton = ' | singleton = ' | ||
+ | </ | ||
==== sets ==== | ==== sets ==== | ||
Ligne 325: | Ligne 336: | ||
* On peut aussi importer directmeent des fonctions et s'en servir : | * On peut aussi importer directmeent des fonctions et s'en servir : | ||
+ | <code python> | ||
from fibo import fib | from fibo import fib | ||
fib(500) | fib(500) | ||
+ | </ | ||
* On peut aussi exécuter des modules comme des scripts : | * On peut aussi exécuter des modules comme des scripts : | ||
+ | <code python> | ||
python fibo.py < | python fibo.py < | ||
+ | </ | ||
Dans ce cas pour gérer les varibles, on utilise : | Dans ce cas pour gérer les varibles, on utilise : | ||
+ | <code python> | ||
if __name__ == " | if __name__ == " | ||
import sys | import sys | ||
fib(int(sys.argv[1])) | fib(int(sys.argv[1])) | ||
+ | </ | ||
**RQ :** on peut aussi exécuter un module directement en ligne de commande : | **RQ :** on peut aussi exécuter un module directement en ligne de commande : | ||
+ | <code python> | ||
python fibo.py 50 | python fibo.py 50 | ||
+ | </ | ||
* Chemin de recherche des modules : | * Chemin de recherche des modules : | ||
Ligne 365: | Ligne 384: | ||
**Exemple :** | **Exemple :** | ||
+ | <code python> | ||
import sound.formats.wavread | import sound.formats.wavread | ||
+ | </ | ||
équivalent à : | équivalent à : | ||
+ | <code python> | ||
from sound.formats import wavread | from sound.formats import wavread | ||
+ | </ | ||
* **RQ :** avec le formalisme from, on peut se passer du préfixe du package : | * **RQ :** avec le formalisme from, on peut se passer du préfixe du package : | ||
+ | <code python> | ||
wavread.play(< | wavread.play(< | ||
+ | </ | ||
* **RQ :** on peut aussi importer une fonction : from sound.formats.wavread import play | * **RQ :** on peut aussi importer une fonction : from sound.formats.wavread import play | ||
Ligne 387: | Ligne 411: | ||
* '' | * '' | ||
+ | <code python> | ||
print(' | print(' | ||
+ | </ | ||
* '' | * '' | ||
+ | <code python> | ||
print(' | print(' | ||
+ | </ | ||
* '' | * '' | ||
+ | <code python> | ||
print(' | print(' | ||
+ | </ | ||
* '' | * '' | ||
+ | <code python> | ||
print(' | print(' | ||
+ | </ | ||
* '' | * '' | ||
+ | <code python> | ||
f = open(' | f = open(' | ||
+ | </ | ||
// | // | ||
Ligne 410: | Ligne 444: | ||
* '' | * '' | ||
+ | <code python> | ||
for line in f: | for line in f: | ||
print(line, end='' | print(line, end='' | ||
+ | </ | ||
* '' | * '' | ||
+ | <code python> | ||
f.write() : | f.write() : | ||
value = ('the answer', | value = ('the answer', | ||
s = str(value) | s = str(value) | ||
f.write(s) | f.write(s) | ||
+ | </ | ||
* '' | * '' | ||
Ligne 425: | Ligne 463: | ||
formalisme with : | formalisme with : | ||
+ | <code python> | ||
with open(' | with open(' | ||
read_data = f.read() | read_data = f.read() | ||
f.closed | f.closed | ||
True | True | ||
+ | </ | ||
json | json | ||
Ligne 453: | Ligne 493: | ||
**Exemple :** attribute references : | **Exemple :** attribute references : | ||
+ | <code python> | ||
class MyClass: | class MyClass: | ||
""" | """ | ||
Ligne 458: | Ligne 499: | ||
def f(self): # method | def f(self): # method | ||
return 'hello world' | return 'hello world' | ||
+ | </ | ||
**Exemple :** instantiation : | **Exemple :** instantiation : | ||
+ | <code python> | ||
x = MyClass() | x = MyClass() | ||
+ | </ | ||
**init :** | **init :** | ||
+ | <code python> | ||
def __init__(self): | def __init__(self): | ||
+ | </ | ||
* On peut créer de nouveaux attributs dans les instances objets (les objets sont " | * On peut créer de nouveaux attributs dans les instances objets (les objets sont " | ||
Ligne 477: | Ligne 523: | ||
* héritage : | * héritage : | ||
+ | <code python> | ||
class DerivedClassName(BaseClassName): | class DerivedClassName(BaseClassName): | ||
+ | </ | ||
* héritage multiple : | * héritage multiple : | ||
+ | <code python> | ||
class DerivedClassName(Base1, | class DerivedClassName(Base1, | ||
+ | </ | ||
**outils :** | **outils :** | ||
+ | <code python> | ||
isinstance(objet, | isinstance(objet, | ||
issubclass(sousclasse, | issubclass(sousclasse, | ||
+ | </ | ||
**iterateur :** '' | **iterateur :** '' | ||
+ | <code python> | ||
class Reverse: | class Reverse: | ||
""" | """ | ||
Ligne 516: | Ligne 569: | ||
x = MyClass() | x = MyClass() | ||
x.f() | x.f() | ||
+ | </ | ||
Si variable ou fonction est précédée de | Si variable ou fonction est précédée de | ||
Ligne 525: | Ligne 579: | ||
**générateur :** '' | **générateur :** '' | ||
+ | <code python> | ||
def reverse(data): | def reverse(data): | ||
for index in range(len(data)-1, | for index in range(len(data)-1, | ||
Ligne 549: | Ligne 604: | ||
list(data[i] for i in range(len(data)-1, | list(data[i] for i in range(len(data)-1, | ||
[' | [' | ||
+ | </ | ||
Ligne 558: | Ligne 613: | ||
Intéragir avec l'OS | Intéragir avec l'OS | ||
+ | <code python> | ||
import os | import os | ||
os.getcwd() | os.getcwd() | ||
Ligne 563: | Ligne 619: | ||
dir(os) # returns a list of all module functions | dir(os) # returns a list of all module functions | ||
help(os) # returns an extensive manual page created from the module' | help(os) # returns an extensive manual page created from the module' | ||
+ | </ | ||
==== module shutils ==== | ==== module shutils ==== | ||
File and dir managment | File and dir managment | ||
+ | <code python> | ||
import shutil | import shutil | ||
shutil.copyfile(' | shutil.copyfile(' | ||
shutil.move('/ | shutil.move('/ | ||
+ | </ | ||
==== module glob ==== | ==== module glob ==== | ||
Wilcard file listing | Wilcard file listing | ||
+ | <code python> | ||
import glob | import glob | ||
glob.glob(' | glob.glob(' | ||
# [' | # [' | ||
+ | </ | ||
==== module sys ==== | ==== module sys ==== | ||
Entre autre pour les arguments du programme, les sorties d' | Entre autre pour les arguments du programme, les sorties d' | ||
+ | <code python> | ||
import sys | import sys | ||
print(sys.argv) | print(sys.argv) | ||
Ligne 586: | Ligne 648: | ||
sys.stderr.write(' | sys.stderr.write(' | ||
sys.exit() | sys.exit() | ||
+ | </ | ||
**RQ :** The getopt module processes sys.argv using the conventions of the Unix getopt() function. More powerful and flexible command line processing is provided by the argparse module. | **RQ :** The getopt module processes sys.argv using the conventions of the Unix getopt() function. More powerful and flexible command line processing is provided by the argparse module. | ||
Ligne 592: | Ligne 655: | ||
Regexp | Regexp | ||
+ | <code python> | ||
import re | import re | ||
re.findall(r' | re.findall(r' | ||
Ligne 597: | Ligne 661: | ||
re.sub(r' | re.sub(r' | ||
# 'cat in the hat' | # 'cat in the hat' | ||
+ | </ | ||
==== module math ==== | ==== module math ==== | ||
Librairies c pour virgule flotante | Librairies c pour virgule flotante | ||
+ | <code python> | ||
import math | import math | ||
math.cos(math.pi / 4) # 0.70710678118654757 | math.cos(math.pi / 4) # 0.70710678118654757 | ||
math.log(1024, | math.log(1024, | ||
+ | </ | ||
==== module random ==== | ==== module random ==== | ||
Selections aléatoires | Selections aléatoires | ||
+ | <code python> | ||
import random | import random | ||
random.choice([' | random.choice([' | ||
Ligne 613: | Ligne 681: | ||
random.random() | random.random() | ||
random.randrange(6) | random.randrange(6) | ||
+ | </ | ||
==== modules urllib / smtplib ==== | ==== modules urllib / smtplib ==== | ||
Ligne 639: | Ligne 708: | ||
==== string ==== | ==== string ==== | ||
from string import Template : | from string import Template : | ||
+ | |||
+ | <code python> | ||
from string import Template | from string import Template | ||
t = Template(' | t = Template(' | ||
t.substitute(village=' | t.substitute(village=' | ||
+ | </ | ||
+ | |||
' | ' | ||
Voir aussi substitute, safe_substitute, | Voir aussi substitute, safe_substitute, |
aidememo/aide_memoire.1533028683.txt.gz · Dernière modification : 2018/07/31 09:18 de ronan