Cours Python
Cours Python
Introduction à Python
18h+18h
Texte
Roland Becker
[Link]@[Link]
Partie 1 : Pourquoi apprendre python
Partie 3 : Algorithmique
• [Link]
• [Link]
• [Link]
Développement d’un programme
aide
éditeur
interpréteur
D’un point de vue pratique
>>> [Link]()
>>> [Link]()
Programming
✤ Similar rules for names of functions, classes (but upper case !), and files
P2 : Les bases du langage
✤ Principes du langage
✤ Structures de données simple
✤ Conditions
✤ Boucles
✤ Help!
✤ Structure de données avancées
✤ Mots réservés
Utilisation spyder
Ligne de commande/python
shell
• pour aller vite
• tester petit éléments
• pas pratique (indentation)
• pas de traces
fichiers
• éditeur de programme !
• exécution simple
• gestion des fichiers
exemple fichier [Link]
Principes du langage
✤ Pas de compilation
✤ Pas de déclarations
✤ Indentation :
✤ Signe =
Une étape:
n étapes:
Loi binomiale
>>> a = "abcdefghijklmnopqrstuvwxyz"
>>> # import string
>>> # a = string.ascii_lowercase
>>> a[-3]
>>> a[:-3]
'slice'
[Link]
Conditions
>>> a = 3
>>> #condition
>>> if a//2==0:
✤ If - elif - else >>> print("pair")
✤ While >>> else:
>>> print("impair")
>>> a = 10
>>> while a:
>>> print("a=",")
>>> a = a -1
>>> print("fin")
Boucles
>>> for i in range(10):
>>> print("i=", i)
>>> a = 2
>>> # erreur de frappe
>>> print(aa)
Structure de données avancées
✤ def Fonctions
✤ list
✤ set Ensemble
✤ dict entrées
Et calculer la position:
>>> l = 'abc'
✤ ensemble
>>> set(l)
✤ comme en mathématique >>> l[::-1]
✤ pas de doublons >>> s = set(l[::-1])
✤ pas d'ordre >>> [Link]('a', 'z')
<latexit sha1_base64="R0Ago9uG8mdSFB8IC4HpyJ8ULXM=">AAAB/XicZY9LS8NAFIVv6qvWV9Slm2AVXJSQiI9uhKIblxXsA5pQJtPbduhMEjITsYTin1FwIW79F27Vf2OSuqjt2ZyPc+4MHC/kTCrL+tEKS8srq2vF9dLG5tb2jr6715RBHFFs0IAHUdsjEjnzsaGY4tgOIyTC49jyRjdZ33rASLLAv1fjEF1BBj7rM0pUGnX1a4djXzkJqRieE7HBUDkT48qYSSsGWSxm065etkwrl7EI9h+Ua0eQq97Vn51eQGOBvqKcSNmxrVC5CYkUoxwnJSeWGBI6IgPspOgTgdJN8q0T4zhMpxucGDSIOcbR7HVChJRj4VVSF0QNM1dDkRntzf2r+lU3YX4YK/Rp2uWYCEKjQJoKH7NZ9vyIRWiemvaFeX53Vq5Vp/ugCAdwCCdgwyXU4Bbq0AAKr/AJX/CtPWkv2pv2Pj0taH9v9uGftI9f4YuVsw==</latexit>
>>> d = {}
>>> d['ana'] = '123'
✤ "dictionnaire"
>>> d['cléo'] = '173'
✤ tableaux associatifs >>> [Link]()
✤ comme une application >>> for k,v in [Link]():
en mathématiques >>> print(k,"-->",v)
✤ clés - valeurs
<latexit sha1_base64="4M7iSyEYSpAMup6aNTrtAjIdGuc=">AAAB2nicZY/LSsNAFIZP6q3WW9SlC4PVUkFCIl6KIBTcuKxgL9KEMplO2tCZzJCZSEvoRnAhbn0Ed271YXwb07QLtf/m/2bOmYHPEzSQyrK+tdzC4tLySn61sLa+sbmlb+80JI8jTOqYUx61PCQJDUJSV4GipCUigphHSdMb3EzmzUcSyYCH92okiMtQLwz8ACOVXnX0ff+qZLQMR3HjwXEKpaHhMCRkehxd++XhcUcvWqaVxZgHewbF6iFkqXX0d6fLccxIqDBFUrZtSyg3QZEKMCXjghNLIhAeoB5ppxgiRqSbZCJj40ikXgZFBuYxJXH0eztBTMoR807SZkj1J636bFK4++9f5VfcJAhFrEiI01mGCUM44tJUZDhOtez/EvPQODXtC/P87qxYrUz9IA97cABlsOESqnALNagDhmf4gE/40hztSXvRXqerOW32Zhf+RHv7Adm9hnk=</latexit>
f :X ! Y
x 7! y = f (x)
Mots réservés
>>> b = a a b 3
>>> b = b + 1 b
a 5 3
>>> b += 1 I
✤ while
✤ for boucle sur une liste ou autre iterable
✤ Répétition d'instructions identiques :
itérations
✤ Pour des boucles complexes, on commence
par écrire une itération
Quelques algorithmes dans python
✤ Choix algorithmiques:
✤ Variables
✤ Fonctions
✤ Type de boucles
✤ Algorithme mathématique != informatique
y f(x)
=
ix ,,,
"
-changement
>>> a, b, niter = 1, 2, 100 c
b
X
de
signe!
L'itération consiste à diviser l'intervalle en comparant trois valeurs
-
110
b
1 Efface
IIII11194
>>> a, b, c, nsam = 1, 2, 2, 1000 -
->
p P((4,y) A)
=
=
>>> # on suppose d'avoir n_in =D1A1 p(R)
=
on estime p!
>>> from random import random
e (:(4+ 73
*
pe
>>> x,y = a+dx*random(), a+dy*random() M
>>> if f(x)<y:
>>> n_in += 1 Il faut ensuite:
• faire la boucle
P4 : L’environnement
✤ [Link]
✤ plusieurs plots
✤ histogrammes
✤ plots 3D
✤ animations
[Link]
>>> import [Link] as plt
>>> x, y = [0, 2, 4], [10,8,9]
>>> [Link](x,y)
>>> [Link]()
>>> [Link](221)
>>> [Link](x, y1)
>>> [Link](222)
>>> [Link]('log')
✤ plusieurs plots dans une axes
>>> [Link](x, y1)
✤ plusieurs plots dans différents axes >>> [Link](223)
✤ axes (et fig) courant >>> [Link](x, y2)
>>> [Link](224)
>>> [Link]('log')
>>> [Link](x, y2)
Random walk (3)
On peut maintenant montrer une m.a.:
>>> [Link](pos,'x-')
>>> [Link]([0,n],[0,0], '--r')
>>> [Link](2,1,1)
>>> [Link](pos,'x-')
>>> [Link]([0,n],[0,0], '--r')
>>> [Link](2,1,2)
>>> p = [d[0] for d in sorted([Link]())]
>>> h = [d[1] for d in sorted([Link]())]
>>> [Link](p, h)
P6 : Langage avancé
✤ Fonctions
✤ Fichier
✤ Formattage
✤ Messages d’erreur
✤ Try - except
✤ Choses diverses
✤ Mutable - immutable
>>> def fct(arg):
Fonctions
>>> # faire qqchose
>>> return res
✤ plusieurs sorties
✤ plusieurs arguments >>> def fct(arg, n=10):
>>> a = [Link]
>>> print("pi={}".format(a))
>>> print("pi={:6.3f}".format(a))
✤ format()
>>> print("pi={:11.5e}".format(a))
✤ C-style >>> s = "chaine_de_charactères"
>>> try:
>>> f = open('[Link]')
>>> s = [Link]()
>>> i = int([Link]())
>>> raise
Choses diverses
>>> l = [i**2 for i in range(10)]
>>> d = {i:i**2 for i in range(10)}
>>> a, b, c = 2, 4, 'abra'
✤ numpy : ndarray
[Link]
✤ numpy : linalg
>>> a = 3*[Link](5)
>>> [Link]("filename",a)
>>> c = [Link]()
>>> a = [Link]("filename")
>>> a = 10*[Link](12)
>>> a[a>5] = -1
>>> i = [Link](t>20)
>>> minval = [Link](t)*np.ones_like(i)
>>> [Link](i, minvals, 'rx')
Random walk (4)
C'est plus rapide et simple avec numpy
n
✤ espace vectoriel euclidien R
✤ addition
✤ multiplication scalaire
✤ produit scalaire
✤ autres fonctions
✤ min, max, argmin, argmax, mean, var, diff, sum, cumsum, sort
m⇥n
✤ mêmes que les vecteurs ! R
✤ multiplication matrice-matrice, matrice-vecteur
✤ calcul valeurs/vecteurs propres, determinants, inversion,..
Création matrices
>>> a = [Link](3)
>>> a = a + 1
>>> print(a)
✤ fonctions par ndim=2 >>> b = [Link](9)
✤ extraction lignes/ >>> b = [Link](3,3)
colonnes >>> print(b)
>>> print(b[2])
>>> print(b[2,:])
>>> print(b[:,1])
[Link]