User Tools

Site Tools


python_cheat_sheet

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Last revisionBoth sides next revision
python_cheat_sheet [2010/04/27 12:15] ginkopython_cheat_sheet [2014/04/01 16:25] ginko
Line 5: Line 5:
   * Encodage <code python># -*- coding: utf-8 -*-</code>   * Encodage <code python># -*- coding: utf-8 -*-</code>
   * Commentaire <code python>#</code>   * Commentaire <code python>#</code>
-  * Import <code python>import nom_module</code>+  * Import <code python>import nom_module</code> ou <code python>from sys import argv</code>NB: cette deuxième manière évite d'avoir à retapper le nom du module en permanence
   * Arguments (passés au script)    * Arguments (passés au script) 
     * Argv: (nécessite l'import du module ''sys'')<code python>argument_1=sys.argv[1]</code> (NB: argv[0] renvoie le nom du script)     * Argv: (nécessite l'import du module ''sys'')<code python>argument_1=sys.argv[1]</code> (NB: argv[0] renvoie le nom du script)
     * Il existe aussi une implémentation de getopt (//cf//. [[http://diveintopython.adrahon.org/scripts_and_streams/command_line_arguments.html|Dive into python - CLI]])     * Il existe aussi une implémentation de getopt (//cf//. [[http://diveintopython.adrahon.org/scripts_and_streams/command_line_arguments.html|Dive into python - CLI]])
 +===== Packaging =====
 +  * Encapsulation pour librairie autonome <code python>if __name__ == "__main__":
 +    main()</code>
 ===== Variables ===== ===== Variables =====
-  * Listes <code python>a=[1, 'c']</code>+  * Listes (mutable)<code python>a=[1, 'c']</code> 
 +  * Sets (mutable) fournit une interface implémentant les ensembles mathématiques (union, réunion, intersection, etc)
     * Ajouter un élément en fin de liste: <code python>a.append('d')</code>     * Ajouter un élément en fin de liste: <code python>a.append('d')</code>
 +  * Tuple (immutable, mais plus performant) <code python>a=('b', 12)</code>
 +  * Matrices: installer et importer numpy ([[http://numpy.scipy.org/]])
   * Casts   * Casts
     * String <code python>str(2)</code>     * String <code python>str(2)</code>
     * Integer <code python>int('2')</code>     * Integer <code python>int('2')</code>
 +    * Tuple <code python>tuple(['a', 2])</code>
 +    * Liste <code python>list(('b', 1))</code>
   * String délimité par ''''' ou ''"''   * String délimité par ''''' ou ''"''
 +    * Sur plusieurs lignes <code python>"""Ceci est
 +une string
 +sur plusieurs lignes"""</code>
     * Concaténation: ''+'' <code python>'Python'+'Cheat Sheet'</code>     * Concaténation: ''+'' <code python>'Python'+'Cheat Sheet'</code>
     * Inclure des variables <code python>print "Il y a %d %s dans mon sac" %(nb_fruit, type_fruit)</code>     * Inclure des variables <code python>print "Il y a %d %s dans mon sac" %(nb_fruit, type_fruit)</code>
Line 25: Line 36:
  
 ===== IO ===== ===== IO =====
-  * Ouvrir un fichier <code python>#'r'=read, 'w'=write +  * Ouvrir un fichier <code python>#'r'=read, 'w'=write, 'a'=append, 'r+'=read & write 
-fichier=open('/path/to/file','r')</code>+fichier=open('/path/to/file','r') 
 +# il faut alors fermer le fichier 
 +# une métode qui referme le fichier proprement: 
 +with open('/tmp/workfile', 'r') as f: 
 +</code>
   * ''IOError'' (erreur d'entrée sortie)   * ''IOError'' (erreur d'entrée sortie)
   * Sortie vers le shell: <code python>print 'hello'</code>   * Sortie vers le shell: <code python>print 'hello'</code>
 +  * Prompt au shell: <code python>foo=raw_input("The Ultimate Question of Life, the Universe, and Everything")</code>NB: il existe également input(), avec laquelle python essaie de deviner le type de la variable entrée. raw_input() se contente de mettre ça dans une string.
 +
 ===== Structure de code ===== ===== Structure de code =====
   * Boucle ''for'' <code python>#pour i de 1 à 5   * Boucle ''for'' <code python>#pour i de 1 à 5
Line 34: Line 51:
     instruction1     instruction1
     instruction2</code>     instruction2</code>
-  * Opérateur ''in'': test permettant de vérifier si un élément est présent dans une liste, un tuple, un fichier, etc.<code python>if 'x' in 'xml':+  * Opérateur ''in'': test permettant de vérifier si un élément est présent dans un itérable (une liste, un tuple, un fichier, etc).<code python>if 'x' in 'xml':
     instruction</code><code python>for line in fichier:     instruction</code><code python>for line in fichier:
     instruction</code>     instruction</code>
 +  * ''Switch''/''case'': en 2.x python ne possède pas de structure switch, on doit se débrouiller avec des ''if ... elif ...'' ou avec la structure suivante:<code python>options = {0 : zero,
 +                1 : sqr,
 +                4 : sqr,
 +                9 : sqr,
 +                2 : even,
 +                3 : prime,
 +                5 : prime,
 +                7 : prime,
 +}
 +
 +def zero():
 +    print "You typed zero.\n"
 +
 +def sqr():
 +    print "n is a perfect square\n"
 +
 +def even():
 +    print "n is an even number\n"
 +
 +def prime():
 +    print "n is a prime number\n"</code>Que l'on peut appeler grâce à:<code python>options[num]()</code>Source: [[http://bytebaker.com/2008/11/03/switch-case-statement-in-python/|bytebaker.com]]
   * ''break'' permet de sortir de la boucle courrante   * ''break'' permet de sortir de la boucle courrante
   * ''continue'' permet de terminer l'itération courrante (passer directement à la suivante, mais sans sortir de la boucle)   * ''continue'' permet de terminer l'itération courrante (passer directement à la suivante, mais sans sortir de la boucle)
-  * ''try ... except ... raise'': Gestion des exceptions<code python>try:+  * ''try ... except ... raise ... else ... finally'': Gestion des exceptions<code python>try:
    instructions    instructions
 except Error: except Error:
-    instructions</code>+    instructions</code>''else'' exécute son bloc si toutes les instructions du ''try'' ont réussi; ''finally'' s'éxécute dans tous les cas. 
 +  * Arrêter le script <code python>quit()</code>
   * Classe: <code python>class formatted_string(parent_class):</code>   * Classe: <code python>class formatted_string(parent_class):</code>
-  * Fonction: <code python>def function_name(arg1,arg2):</code>+  * Fonction: <code python>def function_name(arg1,arg2=10,arg3='foo'):</code>NB: les arguments ''arg2'' et ''arg3'' sont optionnels 
 +    * Expansion des arguments dans un appel de fonction:<code python>args = (1, 2, 3) 
 +function_name(*args) 
 +kwargs = {'arg1': [], 'arg2': 10, 'arg3': 'foo'
 +function_name(**kwargs)</code> 
 +  * Fonction anonyme (jettable, pour usage unique):<code python>lambda arg1, arg2: arg1 + arg2</code>Cf [[http://docs.python.org/tutorial/controlflow.html#lambda-forms|doc officielle]]
   * Test: <code python>if ((test1) & (test2))|(test3):</code>   * Test: <code python>if ((test1) & (test2))|(test3):</code>
  
python_cheat_sheet.txt · Last modified: 2015/01/02 13:03 by ginko