Académique Documents
Professionnel Documents
Culture Documents
Cours Python
Cours Python
Introduction à Python
18h+18h
Texte
Roland Becker
roland.becker@univ-pau.fr
Partie 1 : Pourquoi apprendre python
Partie 3 : Algorithmique
• https://python.sdv.univ-paris-diderot.fr/cours-python.pdf
• https://www.inforef.be/swi/download/apprendre_python3_5.pdf
• https://perso.limsi.fr/pointal/_media/python:cours:courspython3.pdf
Développement d’un programme
aide
éditeur
interpréteur
D’un point de vue pratique
>>> plt.legend()
>>> plt.show()
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 main.py
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'
https://python.developpez.com/cours/apprendre-python-3/
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 >>> s.union('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 >>> d.keys()
✤ comme une application >>> for k,v in d.items():
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
✤ matplotlib.pyplot
✤ plusieurs plots
✤ histogrammes
✤ plots 3D
✤ animations
matplotlib.pyplot
>>> import matplotlib.pyplot as plt
>>> x, y = [0, 2, 4], [10,8,9]
>>> plt.plot(x,y)
>>> plt.show()
>>> plt.subplot(221)
>>> plt.plot(x, y1)
>>> plt.subplot(222)
>>> plt.yscale('log')
✤ plusieurs plots dans une axes
>>> plt.plot(x, y1)
✤ plusieurs plots dans différents axes >>> plt.subplot(223)
✤ axes (et fig) courant >>> plt.plot(x, y2)
>>> plt.subplot(224)
>>> plt.yscale('log')
>>> plt.plot(x, y2)
Random walk (3)
On peut maintenant montrer une m.a.:
>>> plt.plot(pos,'x-')
>>> plt.plot([0,n],[0,0], '--r')
>>> plt.subplot(2,1,1)
>>> plt.plot(pos,'x-')
>>> plt.plot([0,n],[0,0], '--r')
>>> plt.subplot(2,1,2)
>>> p = [d[0] for d in sorted(hist.items())]
>>> h = [d[1] for d in sorted(hist.items())]
>>> plt.bar(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 = math.pi
>>> 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('myfile.txt')
>>> s = f.readline()
>>> i = int(s.strip())
>>> 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
https://numpy.org
✤ numpy : linalg
>>> a = 3*np.ones(5)
>>> np.save("filename",a)
>>> c = a.copy()
>>> a = np.load("filename")
>>> a = 10*np.random.rand(12)
>>> a[a>5] = -1
>>> i = np.where(t>20)
>>> minval = np.min(t)*np.ones_like(i)
>>> plt.plot(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 = np.eye(3)
>>> a = a + 1
>>> print(a)
✤ fonctions par ndim=2 >>> b = np.arange(9)
✤ extraction lignes/ >>> b = b.reshape(3,3)
colonnes >>> print(b)
>>> print(b[2])
>>> print(b[2,:])
>>> print(b[:,1])
np.linalg