59
Introduction M1 MEEF Second DegrØ Maths option Info Introduction Python et prise en main de l’environnement Benjamin Wack ([email protected]) UFR IM2AG, UniversitØ Grenoble Alpes septembre 2018 Remerciements : StØphane Gonnord, Matthieu Moy, Marc de Falco 1 / 43

M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

Introduction

M1 MEEF Second Degré Maths option InfoIntroduction à Python et prise en main de l’environnement

Benjamin Wack ([email protected])

UFR IM2AG, Université Grenoble Alpes

septembre 2018

Remerciements : Stéphane Gonnord, Matthieu Moy, Marc de Falco

1 / 43

Page 2: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

Introduction

Plan

Généralités sur le langage Python

Premiers pas avec l’interprète python

Écriture de programmes dans des fichiers

Constructions et structures de données de base

Divers

Bonus

2 / 43

Page 3: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionGénéralites

Plan

Généralités sur le langage Python

Premiers pas avec l’interprète python

Écriture de programmes dans des fichiers

Constructions et structures de données de base

Divers

Bonus

3 / 43

Page 4: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionGénéralites

Python : en quelques points

I Un langage de scriptI Langage interprété ( 6= langage compilé)I Typage Dynamique ( 6= typage statique)I Indentation significativeI Orientation objetI Gestion automatique de la mémoire (garbage collector)

4 / 43

Page 5: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionGénéralites

Bibliothèque standard Python

I http://docs.python.org/3/library/ : plus de 200packages (approche “batteries included”)

I Structures de données, manipulations de chaînes, ...I Manipulation de fichiers, bases de données, compression ...I Mathématiques (un peu dans la bibliothèque standard,

beaucoup d’autres modules optionnels)I Internet (web, email ...)I Interfaces graphiques, multimedia ...I ...

5 / 43

Page 6: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionGénéralites

Points forts, points faibles

I Dans la vraie vie :I Langage de haut niveau : on peut faire beaucoup avec peu de

codeI Typage dynamique ⇒ lent et gourmand en mémoire

(contournable)I Écosystème très fourniI Facile à apprendre, mais intéressant aussi pour des experts

I Pour la pédagogie :I Démarrage en douceurI Typage dynamique : discutableI Indentation obligatoire : vos élèves sont obligés d’écrire du

code propre (ou presque)

6 / 43

Page 7: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionGénéralites

Points forts, points faibles

I Dans la vraie vie :I Langage de haut niveau : on peut faire beaucoup avec peu de

codeI Typage dynamique ⇒ lent et gourmand en mémoire

(contournable)I Écosystème très fourniI Facile à apprendre, mais intéressant aussi pour des experts

I Pour la pédagogie :I Démarrage en douceurI Typage dynamique : discutableI Indentation obligatoire : vos élèves sont obligés d’écrire du

code propre (ou presque)

6 / 43

Page 8: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionGénéralites

Version 2.x vs 3.y

I Pourquoi est-ce important ?I Le code écrit en Python 2.7 ne marche pas toujours en 3.xI Quelques modules et bibliothèques ont mis du temps à être

portés en Python 3I Mais autant démarrer avec Python 3

I Principaux points d’achoppement :I Entrées / sortiesI Division euclidienne / flottante

I Concrètement, à l’UFR : lancer spyder3 et pas spyder

7 / 43

Page 9: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionGénéralites

Version 2.x vs 3.y

I Pourquoi est-ce important ?I Le code écrit en Python 2.7 ne marche pas toujours en 3.xI Quelques modules et bibliothèques ont mis du temps à être

portés en Python 3I Mais autant démarrer avec Python 3

I Principaux points d’achoppement :I Entrées / sortiesI Division euclidienne / flottante

I Concrètement, à l’UFR : lancer spyder3 et pas spyder

7 / 43

Page 10: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Plan

Généralités sur le langage Python

Premiers pas avec l’interprète python

Écriture de programmes dans des fichiers

Constructions et structures de données de base

Divers

Bonus

8 / 43

Page 11: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Python : premier contact

>>> 2 + 24

>>> le « prompt », ou « invite de commande »⇒ « Bonjour cher utilisateur, que dois-je faire ? »

2 + 2 instruction Python, entrée par l’utilisateur4 réponse de l’interprète Python après exécution.

Variante (IPython) :

In [1]: 2 + 2Out[1]: 4

9 / 43

Page 12: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Python : premier contact

>>> 2 + 24

>>> le « prompt », ou « invite de commande »⇒ « Bonjour cher utilisateur, que dois-je faire ? »

2 + 2 instruction Python, entrée par l’utilisateur4 réponse de l’interprète Python après exécution.

Variante (IPython) :

In [1]: 2 + 2Out[1]: 4

9 / 43

Page 13: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Python : premier contact

>>> 2 + 24

>>> le « prompt », ou « invite de commande »⇒ « Bonjour cher utilisateur, que dois-je faire ? »

2 + 2 instruction Python, entrée par l’utilisateur4 réponse de l’interprète Python après exécution.

Variante (IPython) :

In [1]: 2 + 2Out[1]: 4

9 / 43

Page 14: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Mémoire : les variables

I Les variables ne se déclarent pas.I Définition à la première affectation (mémorisé pour la session

en cours) :>>> x = 42>>> x = x + 1>>> x43>>> x += 1 # plus Pythonesque>>> x44>>> yTraceback (most recent call last):

File "<stdin>", line 1, in <module>NameError: name ’y’ is not defined

10 / 43

Page 15: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Concretement, c’est quoi un interprète ?Option 1 : ligne de commande

I On entre du texte, l’interprète répond avec du texteI Simple, mais peu convivial

11 / 43

Page 16: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Concretement, c’est quoi un interprète ?Option 2 : Un IDE (Spyder, Pyzo...)

I Toujours un interprète, toujours PythonI Plus d’interactivité

12 / 43

Page 17: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Types de données de base

I Entiers : 0, -4, 42, 12345678900000I Flottants : 0.0, 0.5, .5, -1., 1.2e+20

pas « 0,2 » !I Chaînes de caractères :

I "Bonjour"I ’Au revoir’I """Rebonjour"""I "Je vous dis \"bonjour\""I ’Je vous dis "au revoir"’

I Booléens : True et False

13 / 43

Page 18: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Les entiers

I Les opérations standards sur les entiers sont définies :+ - * // % ** (addition, soustraction, multiplication,quotient, reste, exponentiation).

I précision arbitraire

>>> 2 ** 128340282366920938463463374607431768211456>>> 37 // 312>>> 37 % 31

14 / 43

Page 19: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Les flottants

I Les opérations sur les flottants sont + - * / **>>> 3.2 + 1.14.3>>> 2.0 ** 0.51.4142135623730951

I précision, en général, 64-bits.I les nombres sont flottants, pas réels

>>> 0.1 + 0.1 + 0.1 - 0.35.551115123125783e-17>>> format(0.1, ’1.55’) # 55 decimales’0.1000000000000000055511151231257827021181583404541015625’

15 / 43

Page 20: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Opérations mixtes

I entier 2 flottant ⇒ flottant>>> 2 ** 600 - 0.14.149515568880993e+180

I la division simple / entre entiersI En Python 3 : division flottante

>>> 1 / 20.5

16 / 43

Page 21: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Booléens

I Deux valeurs True et FalseI opérateurs logiques : and or not

>>> False or not (True and False)True

I Relations de comparaisons == != < > <= >=

>>> 1 == (3 - 2)True>>> 1 > 2 ** 0.5False

17 / 43

Page 22: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Fonctions mathématiques

I Les fonctions mathématiques sont dans le module mathI Deux possibilités d’accès :

I Import du module et accès depuis le module>>> import math>>> math.sqrt(2.0)1.4142135623730951

I Import spécifique de la fonction et accès direct>>> from math import sqrt>>> sqrt(2.0)1.4142135623730951

18 / 43

Page 23: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Fonctions mathématiques

Listing des fonctions et constantes :

>>> import math>>> dir(math)[’__doc__’, ’__file__’, ’__name__’, ’__package__’, ’acos’,’acosh’, ’asin’, ’asinh’, ’atan’, ’atan2’, ’atanh’, ’ceil’,’copysign’, ’cos’, ’cosh’, ’degrees’, ’e’, ’erf’, ’erfc’,’exp’, ’expm1’, ’fabs’, ’factorial’, ’floor’, ’fmod’,’frexp’, ’fsum’, ’gamma’, ’hypot’, ’isfinite’, ’isinf’,’isnan’, ’ldexp’, ’lgamma’, ’log’, ’log10’, ’log1p’, ’modf’,’pi’, ’pow’, ’radians’, ’sin’, ’sinh’, ’sqrt’, ’tan’, ’tanh’,’trunc’]

Il y a de l’introspection sur les modules.

19 / 43

Page 24: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Aide embarquéeUn doute sur une fonction ?>>> help(math.ceil)Help on built-in function ceil in module math:

ceil(...)ceil(x)

Return the ceiling of x as an int.This is the smallest integral value >= x.

On peut même le faire directement sur le module pour avoir toutel’aide :>>> help(math)

Ce n’est pas réservé aux modules/fonctions fournis.20 / 43

Page 25: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Petits exercices

I Évaluez les expressions suivantes :I 1.0 + 1I "Bonjour " + "a tous"I "Bonjour" + 10I 2 == 2I 2 == 3I (1 == 2) == (3 == 4)

21 / 43

Page 26: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionInterprète

Types et conversions

I Pour récupérer le type :>>> type(2)<class ’int’>>>> type(3.2)<class ’float’>

I Ces valeurs sont manipulables :>>> type(2) == type(3.2)False

I Pour convertir une valeur dans un autre type :>>> str(3.14)’3.14’>>> int(’42’)42

22 / 43

Page 27: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionProgrammes

Plan

Généralités sur le langage Python

Premiers pas avec l’interprète python

Écriture de programmes dans des fichiers

Constructions et structures de données de base

Divers

Bonus

23 / 43

Page 28: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionProgrammes

Mode exécution de scriptCette fois :

I On tape son programme dans un éditeur (inclus dans l’IDE)I On l’enregistre dans un fichierI L’interpréteur « exécute » ce fichier

À retenir : on tapeI Dans l’éditeur :

I les fonctions/programmesI toutes les opérations qu’on veut pouvoir sauverI copy/paste de résultats (interpréteur) commentés

I Dans l’interpréteur :I des petits calculs n’ayant pas vocation à être sauvésI les tests d’un programme écrit par ailleursI une suite d’instructions pour comprendre différents

comportements

24 / 43

Page 29: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionProgrammes

Mode exécution de scriptCette fois :

I On tape son programme dans un éditeur (inclus dans l’IDE)I On l’enregistre dans un fichierI L’interpréteur « exécute » ce fichier

À retenir : on tapeI Dans l’éditeur :

I les fonctions/programmesI toutes les opérations qu’on veut pouvoir sauverI copy/paste de résultats (interpréteur) commentés

I Dans l’interpréteur :I des petits calculs n’ayant pas vocation à être sauvésI les tests d’un programme écrit par ailleursI une suite d’instructions pour comprendre différents

comportements

24 / 43

Page 30: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionProgrammes

Mode exécution de scriptCette fois :

I On tape son programme dans un éditeur (inclus dans l’IDE)I On l’enregistre dans un fichierI L’interpréteur « exécute » ce fichier

À retenir : on tapeI Dans l’éditeur :

I les fonctions/programmesI toutes les opérations qu’on veut pouvoir sauverI copy/paste de résultats (interpréteur) commentés

I Dans l’interpréteur :I des petits calculs n’ayant pas vocation à être sauvésI les tests d’un programme écrit par ailleursI une suite d’instructions pour comprendre différents

comportements

24 / 43

Page 31: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionProgrammes

Premier programme avec entrées-sorties

I Entrons le programme suivant dans l’éditeur :

x = input (’Quel est votre nom ? ’)print (’Bonjour , ’ + x)

I Exécutons-le (plusieurs fois)

print() fait une sortie à l’écran, à ne pas confondre avecl’affichage du résultat qui est fait par défaut dans l’interprète.

25 / 43

Page 32: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionProgrammes

Les entrées / sorties

I La saisie clavier :# Lire une chainestr = input (" Entrez une chaine : ")

# Lire un entier ( lecture de chaine puis conversion )nb = int(input (" Entrez un nombre : "))

I Affichage :print ("toto")print (42)print ("toto ", 42)

I Il y a une conversion automatique des arguments en str.

26 / 43

Page 33: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Plan

Généralités sur le langage Python

Premiers pas avec l’interprète python

Écriture de programmes dans des fichiers

Constructions et structures de données de base

Divers

Bonus

27 / 43

Page 34: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Condition : if/then/else

I Si alorsx = 43if x == 42: # ne pas oublier le ’:’

print ("x vaut 42")print ("et pas autre chose")

# Fin de l’indentation = fin du ifprint ("Suite du programme ")

I Si alors sinonif x == 42:

print ("x vaut 42")else:

print ("x vaut autre chose")

28 / 43

Page 35: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Condition : if/then/else

I Tests imbriqués

if x == 42:print ("x vaut 42")

elif x == 43:print ("x vaut quarante trois")

else:print ("x vaut autre chose")

29 / 43

Page 36: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Boucles

I Boucle conditionnelle (classique)while x <= 42:

x = x + 1

I Boucle inconditionnelle (particulière en Python, mais à l’usageplus pratique à utiliser)for variable in iterable :

instructionsI Qu’est-ce qu’un itérable ?

Liste, chaîne... :s = 0for e in [1 ,2 ,3]:

s += efor c in ’abc ’:

print (c)

30 / 43

Page 37: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Boucles

I Boucle conditionnelle (classique)while x <= 42:

x = x + 1I Boucle inconditionnelle (particulière en Python, mais à l’usage

plus pratique à utiliser)for variable in iterable :

instructions

I Qu’est-ce qu’un itérable ?Liste, chaîne... :s = 0for e in [1 ,2 ,3]:

s += efor c in ’abc ’:

print (c)

30 / 43

Page 38: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Boucles

I Boucle conditionnelle (classique)while x <= 42:

x = x + 1I Boucle inconditionnelle (particulière en Python, mais à l’usage

plus pratique à utiliser)for variable in iterable :

instructionsI Qu’est-ce qu’un itérable ?

Liste, chaîne... :s = 0for e in [1 ,2 ,3]:

s += efor c in ’abc ’:

print (c) 30 / 43

Page 39: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Cas particulier avec les boucles for

I Parcourir les nombres de 0 a N − 1 :for i in range (10):

print (i)# Affiche les nombres de 0 a 9 inclus

I Parcourir les nombres de M à N − 1 :for i in range (7, 10):

print (i)# 7# 8# 9

I Avec un pas :for i in range (0, 10 ,2):

print (i)# Affiche 0, 2, 4, 6, 8 31 / 43

Page 40: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Fonctions

def nom_de_la_fonction (param1 , param2 ):corps de la fonctionindent é...return valeur_a_renvoyer

En Python :I il est optionnel et sans effet d’annoter les arguments par leurs

types ;I on ne déclare pas non plus de type de retour pour la fonction.

def addition (a, b):return a + b

x = addition (42, 3)x = addition (x, 1)

32 / 43

Page 41: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Fonctions

def nom_de_la_fonction (param1 , param2 ):corps de la fonctionindent é...return valeur_a_renvoyer

En Python :I il est optionnel et sans effet d’annoter les arguments par leurs

types ;I on ne déclare pas non plus de type de retour pour la fonction.

def addition (a, b):return a + b

x = addition (42, 3)x = addition (x, 1)

32 / 43

Page 42: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Fonctions

def nom_de_la_fonction (param1 , param2 ):corps de la fonctionindent é...return valeur_a_renvoyer

En Python :I il est optionnel et sans effet d’annoter les arguments par leurs

types ;I on ne déclare pas non plus de type de retour pour la fonction.

def addition (a, b):return a + b

x = addition (42, 3)x = addition (x, 1) 32 / 43

Page 43: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Disposition du code

I Les fin de lignes sont importantesx = 42 # OKx = # Interdit !

42I Coupage possible à l’intérieur des parenthèses :

x = (1 + 2 + 3 + 4 + 5 + # OK6 + 7 + 8 + 9 + 10)

I Mettre plusieurs instructions sur une ligne (à éviter) : « ; »x = 42; print (x)

I Affectation multiple simultanéex, y = 14, 42

x, y = y, x

33 / 43

Page 44: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Disposition du code

I Les fin de lignes sont importantesx = 42 # OKx = # Interdit !

42I Coupage possible à l’intérieur des parenthèses :

x = (1 + 2 + 3 + 4 + 5 + # OK6 + 7 + 8 + 9 + 10)

I Mettre plusieurs instructions sur une ligne (à éviter) : « ; »x = 42; print (x)

I Affectation multiple simultanéex, y = 14, 42

x, y = y, x33 / 43

Page 45: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Pour insister sur quelques pièges

I Essayez le programme suivant :a = 0print ("Je vais compter ")while a <= 10:

print (a)a = a + 1

print ("C’est fini")I Que se passe-t-il si on remplace print(a) par simplement a ?

⇒ ça n’affiche plus rien !I Et si on indente la ligne print("C’est fini") de 4

espaces ?⇒ le print rentre dans la boucle.

L’indentation compte (même indentation avant print(a) et avanta = a + 1, de préférence 4 espaces)

34 / 43

Page 46: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Pour insister sur quelques pièges

I Essayez le programme suivant :a = 0print ("Je vais compter ")while a <= 10:

print (a)a = a + 1

print ("C’est fini")I Que se passe-t-il si on remplace print(a) par simplement a ?⇒ ça n’affiche plus rien !

I Et si on indente la ligne print("C’est fini") de 4espaces ?⇒ le print rentre dans la boucle.

L’indentation compte (même indentation avant print(a) et avanta = a + 1, de préférence 4 espaces)

34 / 43

Page 47: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Pour insister sur quelques pièges

I Essayez le programme suivant :a = 0print ("Je vais compter ")while a <= 10:

print (a)a = a + 1

print ("C’est fini")I Que se passe-t-il si on remplace print(a) par simplement a ?⇒ ça n’affiche plus rien !

I Et si on indente la ligne print("C’est fini") de 4espaces ?

⇒ le print rentre dans la boucle.

L’indentation compte (même indentation avant print(a) et avanta = a + 1, de préférence 4 espaces)

34 / 43

Page 48: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Pour insister sur quelques pièges

I Essayez le programme suivant :a = 0print ("Je vais compter ")while a <= 10:

print (a)a = a + 1

print ("C’est fini")I Que se passe-t-il si on remplace print(a) par simplement a ?⇒ ça n’affiche plus rien !

I Et si on indente la ligne print("C’est fini") de 4espaces ?⇒ le print rentre dans la boucle.

L’indentation compte (même indentation avant print(a) et avanta = a + 1, de préférence 4 espaces) 34 / 43

Page 49: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Exercice : somme des N premiers entiers

I Écrire un programme qui calcule la somme des entiers de 0 àN (sans utiliser N(N + 1)/2, ça serait de la triche !)

n = int( input(" Entrer N : "))

sum = 0for i in range(n + 1):

sum = sum + i

print ("La somme des entiers de 0 a",n, "est :", sum)

35 / 43

Page 50: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionConstructions

Exercice : somme des N premiers entiers

I Écrire un programme qui calcule la somme des entiers de 0 àN (sans utiliser N(N + 1)/2, ça serait de la triche !)

n = int( input (" Entrer N : "))

sum = 0for i in range(n + 1):

sum = sum + i

print ("La somme des entiers de 0 a",n, "est :", sum)

35 / 43

Page 51: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionDivers

Plan

Généralités sur le langage Python

Premiers pas avec l’interprète python

Écriture de programmes dans des fichiers

Constructions et structures de données de base

Divers

Bonus

36 / 43

Page 52: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionDivers

Les commentaires

I Tout ce qui suit un # sur une ligne est ignoré par l’interprète :

a = 0 # initialisation de aprint ("Je vais compter ")while a <= 10: # blablabla

print (a) # encore du blablaa = a + 1

print ("C’est fini")

I Très utile pour s’y retrouver dans le code

37 / 43

Page 53: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionDivers

Les erreurs à l’exécutionI Mettez en commentaire ou supprimez l’initialisation de a :

# a = 0print ("Je vais compter ")while a <= 10:

print(a)a = a + 1

print ("C’est fini")

I Il peut se passer deux choses :I Notre éditeur de texte peut nous avertir que quelque chose ne

va pas (les versions récentes de Spyder le font).I Si on exécute le programme, on obtient une erreur à

l’exécution (après le premier affichage) :Je vais compterTraceback (most recent call last):

File "/tmp/hello.py", line 9, in <module>while a <= 10:

NameError: name ’a’ is not defined

38 / 43

Page 54: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionDivers

Les erreurs à l’exécutionI Mettez en commentaire ou supprimez l’initialisation de a :

# a = 0print ("Je vais compter ")while a <= 10:

print(a)a = a + 1

print ("C’est fini")I Il peut se passer deux choses :

I Notre éditeur de texte peut nous avertir que quelque chose neva pas (les versions récentes de Spyder le font).

I Si on exécute le programme, on obtient une erreur àl’exécution (après le premier affichage) :Je vais compterTraceback (most recent call last):

File "/tmp/hello.py", line 9, in <module>while a <= 10:

NameError: name ’a’ is not defined38 / 43

Page 55: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionDivers

Les erreurs de syntaxe

I Supprimez maintenant les « : » de la boucle while :

a = 0print ("Je vais compter ")while a <= 10 # plus de :

print (a)a = a + 1

print ("C’est fini")

I Cette fois-ci, on obtient l’erreur avant le début de l’exécution(même "Je vais compter" n’est plus affiché).

39 / 43

Page 56: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionBonus

Plan

Généralités sur le langage Python

Premiers pas avec l’interprète python

Écriture de programmes dans des fichiers

Constructions et structures de données de base

Divers

Bonus

40 / 43

Page 57: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionBonus

Exercice : Calcul de racine carrée par méthode de Héron(cas particulier de méthode de Newton)

xn+1 = xn −f (xn)

f ′(xn)avec f (x) = x2 − a

xn+1 = xn −x2

n − a2xn

xn+1 =xn + a/xn

2

41 / 43

Page 58: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionBonus

Racine carrée, solution 1Nombre d’itérations fixe

import math # Pour pouvoir utiliser math.sqrt ()

a = int(input (" Racine de ? "))

g = afor i in range (10):

g = (g + (a / g)) / 2.0# decommenter pour voir la progression# print(g)

print (g, " devrait etre =", math.sqrt(a))

42 / 43

Page 59: M1 MEEF Second Degré Maths option Info - Introduction à ... · Introduction Généralites Python:enquelquespoints I Unlangagedescript I Langageinterprété(6= langagecompilé) I

IntroductionBonus

Racine carrée, solution 2Contrôle de la précision

import math # Pour pouvoir utiliser math.sqrt ()

a = int(input (" Racine de ? "))

g = awhile abs(g ** 2 - a) > 0.0001:

g = (g + (a / g)) / 2.0# decommenter pour voir la progression# print(g)

print (g, " devrait etre =", math.sqrt(a))

43 / 43