Python 3 : instructions avancées
I - Les listes
En Python, une liste s'écrit entre crochets : [élément1, élément2, …].
Utilisation d'une liste (instruction Python)
liste1 = [-4, 5.2, "bonjour", 'a', -4] # création d'une liste
liste2 = [] # liste vide
nbre_elements = len(liste1) # nombre d'éléments : 5
liste1.append("élément") # ajoute un élément à la fin
debut_liste = liste1[0] # premier élément : -4
dernier = liste1[-1] # dernier élément
del liste1[2] # supprime l'élément d'indice 2 ("bonjour")
liste1.remove(-4) # supprime le premier élément égal à -4
Parcourir une liste et créer une liste en compréhension
notes = [12, 8, 15, 10, 17]
somme = 0
for n in notes: # n prend successivement chaque valeur de la liste
somme = somme + n
print(somme / len(notes)) # moyenne : 12.4
carres = [k ** 2 for k in range(1, 6)] # [1, 4, 9, 16, 25]
II - Les fonctions
- On déclare une fonction avec
def nom_fonction(paramètres):; - si elle renvoie une valeur, on écrit dans son corps
return valeur; - on l'appelle en écrivant son nom suivi des valeurs des paramètres entre parenthèses.
Fonction qui ne renvoie rien (instruction Python)
def affiche_message():
print("La fonction a été appelée.")
affiche_message()
def affiche_date(jour, mois, annee):
print("Aujourd'hui, nous sommes le", jour, mois, annee)
affiche_date(21, "avril", 2019)
Fonction qui renvoie une valeur (instruction Python)
def f(x):
return 3 * x ** 2 - 2 * x + 1
print(f(2)) # affiche 9
def valeur_absolue(x):
if x >= 0:
return x
else:
return -x
print(valeur_absolue(-7)) # affiche 7
def renvoie_date(jour, mois, annee):
# str convertit un nombre en chaîne de caractères
return "Nous sommes le " + str(jour) + " " + mois + " " + str(annee)
print(renvoie_date(21, "avril", 2019))
III - Modules et packages
.py) contenant des fonctions utilisables dans d'autres programmes du même répertoire. Python fournit aussi des modules de base, utilisables directement.from nom_module import nom_fonctionimporte une fonction d'un module ;from nom_module import *importe toutes ses fonctions.
Utilisation d'un module (instruction Python)
# Fichier module.py
def aire_carre(cote):
return cote ** 2
# Programme qui utilise module.py
from module import aire_carre
print(aire_carre(3)) # 9
| Module | Contenu |
|---|---|
random | valeurs aléatoires (random(), randint(a, b)…) |
math | fonctions mathématiques (sqrt, exp, log, pi…) |
sys | fonctions liées au système Python |
os | interaction avec le système d'exploitation |
time | travail avec le temps |
calendar | fonctions de calendrier |
Utilisation des modules math et random
from math import sqrt, log from random import randint, random print(sqrt(2)) # environ 1.414 print(log(10)) # logarithme népérien : environ 2.303 de = randint(1, 6) # entier aléatoire entre 1 et 6 (inclus) u = random() # réel aléatoire dans [0 ; 1[
Plusieurs modules regroupés dans un même dossier forment un package. On importe une fonction avec from nom_package.nom_module import nom_fonction.
IV - Les graphiques
Pour tracer des graphiques, on utilise le module pyplot du package matplotlib (documentation : matplotlib.org).
Utilisation de pyplot (instruction Python)
from matplotlib.pyplot import *
scatter(4, 3.6, color="blue") # un point
plot([1, 7], [8, 3], "--", color="red") # segment en pointillés de (1;8) à (7;3)
x = []
y = []
for i in range(100): # courbe de la fonction carré sur [-4 ; 5,9]
var = -4 + 0.1 * i
x.append(var)
y.append(var ** 2)
plot(x, y, color="green", label="y = x²", linewidth=3)
legend() # affiche la légende
show() # affiche la figure
Aperçu de la figure obtenue :
Python 3: advanced instructions
I - Lists
In Python, a list is written between square brackets: [element1, element2, …].
Using a list (Python instruction)
liste1 = [-4, 5.2, "bonjour", 'a', -4] # create a list
liste2 = [] # empty list
nbre_elements = len(liste1) # number of elements: 5
liste1.append("élément") # add an element at the end
debut_liste = liste1[0] # first element: -4
dernier = liste1[-1] # last element
del liste1[2] # delete the element of index 2 ("bonjour")
liste1.remove(-4) # delete the first element equal to -4
Looping over a list and list comprehension
notes = [12, 8, 15, 10, 17]
somme = 0
for n in notes: # n takes each value of the list in turn
somme = somme + n
print(somme / len(notes)) # mean: 12.4
carres = [k ** 2 for k in range(1, 6)] # [1, 4, 9, 16, 25]
II - Functions
- A function is declared with
def function_name(parameters):; - if it returns a value, we write
return valuein its body; - it is called by writing its name followed by the parameter values in brackets.
Function returning nothing (Python instruction)
def affiche_message():
print("The function has been called.")
affiche_message()
def affiche_date(jour, mois, annee):
print("Today is", jour, mois, annee)
affiche_date(21, "April", 2019)
Function returning a value (Python instruction)
def f(x):
return 3 * x ** 2 - 2 * x + 1
print(f(2)) # displays 9
def valeur_absolue(x):
if x >= 0:
return x
else:
return -x
print(valeur_absolue(-7)) # displays 7
def renvoie_date(jour, mois, annee):
# str converts a number into a string
return "Today is " + str(jour) + " " + mois + " " + str(annee)
print(renvoie_date(21, "April", 2019))
III - Modules and packages
.py) containing functions that can be used in other programs in the same folder. Python also provides built-in modules.from module_name import function_nameimports a function from a module;from module_name import *imports all its functions.
Using a module (Python instruction)
# File module.py
def aire_carre(cote):
return cote ** 2
# Program using module.py
from module import aire_carre
print(aire_carre(3)) # 9
| Module | Content |
|---|---|
random | random values (random(), randint(a, b)…) |
math | mathematical functions (sqrt, exp, log, pi…) |
sys | functions related to the Python system |
os | interaction with the operating system |
time | working with time |
calendar | calendar functions |
Using the math and random modules
from math import sqrt, log from random import randint, random print(sqrt(2)) # about 1.414 print(log(10)) # natural logarithm: about 2.303 de = randint(1, 6) # random integer between 1 and 6 (included) u = random() # random real in [0 ; 1[
Several modules grouped in one folder form a package. A function is imported with from package_name.module_name import function_name.
IV - Graphs
To draw graphs, we use the pyplot module of the matplotlib package (documentation: matplotlib.org).
Using pyplot (Python instruction)
from matplotlib.pyplot import *
scatter(4, 3.6, color="blue") # one point
plot([1, 7], [8, 3], "--", color="red") # dashed segment from (1;8) to (7;3)
x = []
y = []
for i in range(100): # curve of the square function on [-4 ; 5.9]
var = -4 + 0.1 * i
x.append(var)
y.append(var ** 2)
plot(x, y, color="green", label="y = x²", linewidth=3)
legend() # shows the legend
show() # shows the figure
Preview of the figure obtained:
Python 3: instrucciones avanzadas
I - Las listas
En Python, una lista se escribe entre corchetes: [elemento1, elemento2, …].
Uso de una lista (instrucción Python)
liste1 = [-4, 5.2, "bonjour", 'a', -4] # creación de una lista
liste2 = [] # lista vacía
nbre_elements = len(liste1) # número de elementos: 5
liste1.append("élément") # añade un elemento al final
debut_liste = liste1[0] # primer elemento: -4
dernier = liste1[-1] # último elemento
del liste1[2] # borra el elemento de índice 2 ("bonjour")
liste1.remove(-4) # borra el primer elemento igual a -4
Recorrer una lista y lista por comprensión
notes = [12, 8, 15, 10, 17]
somme = 0
for n in notes: # n toma sucesivamente cada valor de la lista
somme = somme + n
print(somme / len(notes)) # media: 12.4
carres = [k ** 2 for k in range(1, 6)] # [1, 4, 9, 16, 25]
II - Las funciones
- Una función se declara con
def nombre_funcion(parámetros):; - si devuelve un valor, se escribe
return valoren su cuerpo; - se llama escribiendo su nombre seguido de los valores de los parámetros entre paréntesis.
Función que no devuelve nada (instrucción Python)
def affiche_message():
print("La función ha sido llamada.")
affiche_message()
def affiche_date(jour, mois, annee):
print("Hoy es", jour, mois, annee)
affiche_date(21, "abril", 2019)
Función que devuelve un valor (instrucción Python)
def f(x):
return 3 * x ** 2 - 2 * x + 1
print(f(2)) # muestra 9
def valeur_absolue(x):
if x >= 0:
return x
else:
return -x
print(valeur_absolue(-7)) # muestra 7
def renvoie_date(jour, mois, annee):
# str convierte un número en cadena de caracteres
return "Hoy es " + str(jour) + " de " + mois + " de " + str(annee)
print(renvoie_date(21, "abril", 2019))
III - Módulos y paquetes
.py) con funciones utilizables en otros programas de la misma carpeta. Python también ofrece módulos de base.from nombre_modulo import nombre_funcionimporta una función de un módulo;from nombre_modulo import *importa todas sus funciones.
Uso de un módulo (instrucción Python)
# Archivo module.py
def aire_carre(cote):
return cote ** 2
# Programa que usa module.py
from module import aire_carre
print(aire_carre(3)) # 9
| Módulo | Contenido |
|---|---|
random | valores aleatorios (random(), randint(a, b)…) |
math | funciones matemáticas (sqrt, exp, log, pi…) |
sys | funciones del sistema Python |
os | interacción con el sistema operativo |
time | trabajo con el tiempo |
calendar | funciones de calendario |
Uso de los módulos math y random
from math import sqrt, log from random import randint, random print(sqrt(2)) # aproximadamente 1.414 print(log(10)) # logaritmo neperiano: aproximadamente 2.303 de = randint(1, 6) # entero aleatorio entre 1 y 6 (incluidos) u = random() # real aleatorio en [0 ; 1[
Varios módulos agrupados en una carpeta forman un paquete. Una función se importa con from nombre_paquete.nombre_modulo import nombre_funcion.
IV - Los gráficos
Para dibujar gráficos se usa el módulo pyplot del paquete matplotlib (documentación: matplotlib.org).
Uso de pyplot (instrucción Python)
from matplotlib.pyplot import *
scatter(4, 3.6, color="blue") # un punto
plot([1, 7], [8, 3], "--", color="red") # segmento punteado de (1;8) a (7;3)
x = []
y = []
for i in range(100): # curva de la función cuadrado en [-4 ; 5,9]
var = -4 + 0.1 * i
x.append(var)
y.append(var ** 2)
plot(x, y, color="green", label="y = x²", linewidth=3)
legend() # muestra la leyenda
show() # muestra la figura
Vista previa de la figura obtenida: