Python Greg McShane January 28, 2014 Canopy : https://www.enthought.com/products/canopy/ Python packages : I Numpy http://www.numpy.org/ I Scipy http://scipy.org/ I Matplotlib http://matplotlib.org/ I Pandas http://pandas.pydata.org/ IPython (CLI)http://ipython.org/ Télécharger : https://www.enthought.com/downlroads/ Komodo Edit : http://www.activestate.com/komodo-edit Télécharger : http://www.activestate.com/komodo-edit/downloads Modif à faire : http: // community. activestate. com/ forum-topic/ executing-python-code-within-komodo-edit 1. Langage de scripte (pas de compilation avant exectution) 2. Organisé par modules (enormement de modules) 3. facile à lire. 4. Pas de delimiter de block Entiers >>> 123 123 >>> type(123) <type ’int’> >>> 123**2 15129 >>> 123/1 123 >>> 123/124 0 >>> 123 % 5 3 >>> 123 % 17 4 >>> x = 123 + 5 >>> y = 123 + 1.1 >>> type(x),type(y) (<type ’int’>, <type ’float’>) >>> Complexes >>> z = 1J >>> type(z) <type ’complex’> >>> z**2 (-1+0j) >>> 1/z -1j >>> z.real(),z.imag() Traceback (most recent call last): File "<pyshell#22>", line 1, in <module> z.real(),z.imag() TypeError: ’float’ object is not callable >>> z.real,z.imag (0.0, 1.0) >>> z/2 0.5j >>> z.conjugate() -1j Operateurs affectation = arithmetique + - * / % ** commentaires # formatage de chaine de caracteres % logique and,or, not, != comparaison ==, in, <, > Affectation >>> >>> 1 >>> 2 >>> >>> >>> 2 a,b = 1,2 a b L = range(3) x,y, z = L z Math module >>> import math >>> dir(math) [’__doc__’, ’__name__’, ’__package__’, ’acos’, ’acosh’, ’asin’, ’asinh’, ’atan’, ’atan2’, ’atanh’, ’ceil’, ’copysign’, ’cos’, ’cosh’, ’degrees’, ’e’, ’exp’, ’fabs’, ’factorial’, ’floor’, ’fmod’, ’frexp’, ’fsum’, ’hypot’, ’isinf’, ’isnan’, ’ldexp’, ’log’, ’log10’, ’log1p’, ’modf’, ’pi’, ’pow’, ’radians’, ’sin’, ’sinh’, ’sqrt’, ’tan’, ’tanh’, ’trunc’] >>> tan(pi) Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> tan(pi) NameError: name ’tan’ is not defined >>> from math import * >>> tan(pi) -1.2246063538223773e-16 numpy et vectors https://pypi.python.org/pypi/numpy >>> import numpy >>> dir(numpy) [’ALLOW_THREADS’, ’BUFSIZE’, ’CLIP’, ’ComplexWarning’, ’DataSource’, ... ’arange’, ’arccos’, ’arccosh’, ’arcsin’, ’arcsinh’, ’arctan’, ’arctan2’, ’arct .... >>> x = numpy.array([1,2,3]) >>> y = numpy.array([4,5,6]) >>> x+ y array([5, 7, 9]) >>> 2*x array([2, 4, 6]) >>> 5*x array([ 5, 10, 15]) >>> numpy.vdot(x,y) 32 Listes http://fr.wikibooks.org/wiki/Apprendre_%C3%A0_programmer_avec_Python/ Approfondir_les_structures_de_donn%C3%A9es#Le_point_sur_les_listes >>> >>> [0, >>> 1 >>> 9 >>> [1, >>> [0, >>> [3] >>> [3, >>> [0, >>> 9 >>> 10 L = range(10) L 1, 2, 3, 4, 5, 6, 7, 8, 9] L[1] L[-1] L[1:] 2, 3, 4, 5, 6, 7, 8, 9] L[:-2] 1, 2, 3, 4, 5, 6, 7] L[3:4] L[3:6] 4, 5] L + [11] 1, 2, 3, 4, 5, 6, 7, 8, 9, 11] L.pop() len(L) Listes >>> >>> >>> >>> [2, >>> >>> [0, >>> 4 >>> (4, import random L = range(5) random.shuffle(L) L 3, 0, 4, 1] L.sort() L 1, 2, 3, 4] max(L) max(L),min(L) 0) (4, 0) = tuple = liste de taille fixe >>> type((4,0)) <type ’tuple’> >>> (4,0)[0] 4 >>> len((4,0)) 2 >>> x,y = (4,0) >>> x 4 Chaines de caracteres >>> ss = ’greg’ >>> ss[0] ’g’ >>> ss[1:] ’reg’ >>> ss + " mcshane" ’greg mcshane’ >>> ss.upper() ’GREG’ >>> ss.find(’g’) 0 >>> ss.find(’r’) 1 >>> ss.replace(’g’,’p’) ’prep’ Conditions for x in range(5): if x % 2 == 1 : print x for x in range(10): if x % 2 in [0,3] : print x for x in range(10): if 1< x % 5 < 3 : print x Boucles for k in range(5): print k for k in range(5): if k % 2 : continue print k k = 5 while 1: k -= 1 print k if k < 0 : break import string for x in string.lowercase[:5]: print x.upper() Dictionnaires http://fr.wikibooks.org/wiki/Apprendre_%C3%A0_programmer_avec_Python/ Approfondir_les_structures_de_donn%C3%A9es#Les_dictionnaires >>> dd = ’a’ : 1, ’b’ : 2 >>> typedd SyntaxError: invalid syntax >>> type(dd) <type ’dict’> >>> dd[’a’] 1 >>> dd[’b’] 2 >>> dd.items() [(’a’, 1), (’b’, 2)] >>> dd = dict([(c,c.upper()) for c in string.lowercase]) >>> dd[’z’] ’Z’ >>> dd[’Z’] Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> dd[’Z’] KeyError: ’Z’ Fonctions Syntaxe : def div2(x): return x/2 Récursive : def fact(n): ’’’n int’’’ if n == 1: return 1 if n > 1: return n*fact(n-1) Valeur par défaut: def f(x, n = 2): return x**n >>> f(3) 9 >>> f(3,3) 27 Fonctions avancées : closures Focntion dont le résultat est fonction : def f(x): def g(y): return x*y return g print "gg(4) = ", gg(4) >>print "f(5) =", f(5) f(5) = <function g at 0x2993b0> >>print "f(5)(4) = ", f(5)(4) f(5)(4) = 20 >>gg = f(5) >>x = 10 >>print "gg(4) = ", gg(4) gg(4) = 20 Print >>> print 5 5 >>> print ’*’*5 ***** >>> print ’*\t’*5 * * * * * >>> print ’*\n’*5 * * * * * >>> print ’%s.jpg’%’hello’ hello.jpg >>> print ’%.5f’%sqrt(5) 2.23607 >>> >>> L = [’a’,’b’,’c’,’d’] >>> print ’-’.join(L) a-b-c-d >>> Construction des listes >>> range(10,20,2) [10, 12, 14, 16, 18] >>> ss = ’I am alone’ >>> ss.split() [’I’, ’am’, ’alone’] >>> L = [ x for x in range(100) if x % 5 == 3 and (x / 10) % 2 == 0 ] >>> L [3, 8, 23, 28, 43, 48, 63, 68, 83, 88] L = [] for x in range(5): L.append((x,x**2)) print L >>> [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)] >>> [(x, x**2) for x in range(5)] [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)] Regles 1. il y a pas de delimiteurs comme en C/Java 10: while (1) 11: { 12: counter ++; 13: if (counter > 10) 14: break; 15: } 2. Noms de variables I I I I I I I I I m, n, i, j, k entiers x, y flottants, points z, w complexes u, v vecteurs, points L liste p, q points, ou denominateur, numerateur c ou cc un caractere s ou mieux ss une chaine de caracteres. Interdit : o, O, I , l 3. Le nom d’une fonction/methode doit correspondre à sa fonction. I I pdf2ps, png2jpg, pdflatex getX, setX 4. Les expressions et les espaces : x + y 2*x + 3*y a = 5 5. Utiliser un minimum de lignes tout en restant lisible. 6. Utiliser les commentaires que pour signaler les problemes. Regles >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren’t special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you’re Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it’s a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let’s do more of those!