Python 3 : les bases
L'objectif de ce cours est d'introduire la mise en œuvre d'algorithmes à l'aide du langage Python.
I - Premières instructions en langage Python
• Insertion d'un commentaire
Un commentaire est précédé du symbole # : la suite de la ligne est ignorée lors de l'exécution. Il facilite la compréhension du programme.
Insérer un commentaire (instruction Python)
# Ceci est un commentaire sur une seule ligne en Python.
• Utilisation d'une variable
Une variable est associée à un espace mémoire et stocke une valeur (nombre, chaîne de caractères…). Son nom commence par une lettre et ne contient ni espace ni caractère spécial (seul le tiret bas _ est autorisé). On affecte une valeur avec le symbole =.
Utilisation d'une variable (instruction Python)
# On crée une variable nombre1 et on lui affecte la valeur 5 nombre1 = 5 nombre2 = -3.4 somme = nombre1 + nombre2 produit = nombre1 * nombre2 quotient = nombre1 / nombre2 # Puissance : nombre1 au cube puissance3 = nombre1 ** 3 phrase = "Hello World !"
Remarque : en Python, la virgule décimale s'écrit avec un point : $-3{,}4$ s'écrit -3.4. Le quotient entier s'obtient avec // et le reste de la division euclidienne avec % (exemple : 17 // 5 vaut $3$ et 17 % 5 vaut $2$).
• Affichage dans la console
Pour afficher des informations, on utilise l'instruction print.
Affichage dans la console (instruction Python)
# Afficher un message (avec guillemets)
print("J'aime bien apprendre le langage Python.")
# Afficher le contenu d'une variable (sans guillemets)
phrase = "Hello World !"
print(phrase)
# Combiner messages et variables
nom = "Pierre"
age = 16
print(nom, "est âgé de", age, "ans.")
• Saisie au clavier
L'instruction input stocke une chaîne de caractères saisie au clavier. Pour un nombre, on la convertit avec int (entier), float (décimal) ou eval (expression quelconque, par exemple 7/2).
Saisie au clavier (instruction Python)
phrase = input("Entrer votre nom : ")
nombre_entier = int(input("Entrer un nombre entier : "))
nombre_decimal = float(input("Entrer un nombre décimal : "))
nombre_reel = eval(input("Entrer un nombre réel : "))
II - Instructions conditionnelles
Certaines instructions ne sont exécutées que si une condition est satisfaite. Les opérateurs de comparaison $=$, $\neq$, $<$, $>$, $\leqslant$, $\geqslant$ s'écrivent en Python ==, !=, <, >, <=, >=.
• Si … alors …
En Python : if condition: ; le bloc d'instructions qui suit est décalé d'une tabulation (4 espaces) : il est indenté.
Si … alors … (instruction Python)
mot_de_passe = input("Entrer le mot de passe : ")
if mot_de_passe == "sesame":
print("Merci. Vous pouvez entrer.")
Remarque : Python est sensible à la casse : Sesame et sesame sont différents.
Une condition peut combiner plusieurs tests avec les opérateurs logiques ET (and) et OU (or) : « c1 ET c2 » est vraie si les deux sont vraies ; « c1 OU c2 » est vraie si au moins l'une est vraie.
and, or (instruction Python)
nombre = float(input("Entrer un nombre : "))
if nombre >= 1 and nombre <= 2:
print("Le nombre appartient à [1;2].")
if nombre < 1 or nombre > 2:
print("Le nombre appartient à ]-inf;1[ U ]2;+inf[.")
• Si … alors … sinon …
Si … alors … sinon … (instruction Python)
mot_de_passe = input("Entrer le mot de passe : ")
if mot_de_passe == "sesame":
print("Merci. Vous pouvez entrer.")
else:
print("Désolé. Mot de passe incorrect.")
• Branchement conditionnel
if … elif … else (instruction Python)
age = int(input("Entrer votre âge : "))
if age < 3:
print("Vous êtes un bébé.")
elif age < 12:
print("Vous êtes un enfant.")
elif age < 18:
print("Vous êtes un adolescent.")
else:
print("Vous êtes un adulte.")
Remarque : avec elif, une condition n'est testée que si les précédentes sont fausses : il est inutile de réécrire age >= 3. Le else est facultatif.
III - Instructions itératives (boucles)
On utilise une boucle pour répéter un même bloc d'instructions.
• Boucle bornée : pour … allant de … à …
Le nombre d'itérations est connu à l'avance : un compteur est incrémenté à chaque passage. En Python : for i in range(debut, fin, pas):, ou range(debut, fin) (pas $1$), ou range(fin) (début $0$, pas $1$).
Attention : la valeur fin est exclue : range(0, 10, 2) donne $0, 2, 4, 6, 8$ et range(3) donne $0, 1, 2$.
for (instruction Python)
# Calcul de 2 à la puissance 3
a = 1
for compteur in range(3):
a = a * 2
print("2 puissance 3 vaut :", a)
# Somme des carrés des nombres pairs inférieurs à 10
somme_carres = 0
for i in range(0, 10, 2):
somme_carres = somme_carres + i * i
print("Somme :", somme_carres) # affiche 120
• Boucle non bornée : tant que … faire
On répète un bloc d'instructions tant qu'une condition est vraie ; le test est fait au début de chaque passage et le nombre d'itérations n'est pas connu à l'avance. En Python : while condition:.
while (instruction Python)
# L'utilisateur doit taper un nombre positif ou nul
x = -1
while x < 0:
x = float(input("Entrer un nombre positif ou nul : "))
print("La valeur de x est", x)
Application : algorithme de seuil
Un capital de $1\,000$ € est placé à $4\,\%$ par an. Au bout de combien d'années dépasse-t-il $1\,500$ € ?
C = 1000
n = 0
while C <= 1500:
C = C * 1.04
n = n + 1
print(n) # affiche 11
Python 3: the basics
The aim of this lesson is to implement algorithms with the Python language.
I - First Python instructions
• Comments
A comment starts with the symbol #: the rest of the line is ignored when running. It makes the program easier to understand.
Inserting a comment (Python instruction)
# This is a one-line comment in Python.
• Using a variable
A variable is linked to a memory space and stores a value (number, string…). Its name starts with a letter and contains no space or special character (only the underscore _ is allowed). A value is assigned with the symbol =.
Using a variable (Python instruction)
# We create a variable nombre1 and assign it the value 5 nombre1 = 5 nombre2 = -3.4 somme = nombre1 + nombre2 produit = nombre1 * nombre2 quotient = nombre1 / nombre2 # Power: nombre1 cubed puissance3 = nombre1 ** 3 phrase = "Hello World !"
Remark : in Python, decimals are written with a point: $-3.4$ is -3.4. Integer division is // and the remainder is % (example: 17 // 5 is $3$ and 17 % 5 is $2$).
• Displaying in the console
To display information, we use the instruction print.
Displaying in the console (Python instruction)
# Display a message (with quotes)
print("I like learning Python.")
# Display the content of a variable (without quotes)
phrase = "Hello World !"
print(phrase)
# Combine messages and variables
nom = "Pierre"
age = 16
print(nom, "is", age, "years old.")
• Keyboard input
The instruction input stores a string typed on the keyboard. For a number, convert it with int (integer), float (decimal) or eval (any expression, e.g. 7/2).
Keyboard input (Python instruction)
phrase = input("Enter your name: ")
nombre_entier = int(input("Enter an integer: "))
nombre_decimal = float(input("Enter a decimal: "))
nombre_reel = eval(input("Enter a real number: "))
II - Conditional statements
Some instructions are only run if a condition holds. The comparison operators $=$, $\neq$, $<$, $>$, $\leqslant$, $\geqslant$ are written in Python ==, !=, <, >, <=, >=.
• If … then …
In Python: if condition:; the following block is shifted by one tab (4 spaces): it is indented.
If … then … (Python instruction)
mot_de_passe = input("Enter the password: ")
if mot_de_passe == "sesame":
print("Thank you. You may enter.")
Remark : Python is case-sensitive: Sesame and sesame are different.
A condition can combine several tests with the logical operators AND (and) and OR (or): “c1 AND c2” is true if both are true; “c1 OR c2” is true if at least one is true.
and, or (Python instruction)
nombre = float(input("Enter a number: "))
if nombre >= 1 and nombre <= 2:
print("The number is in [1;2].")
if nombre < 1 or nombre > 2:
print("The number is in ]-inf;1[ U ]2;+inf[.")
• If … then … else …
If … then … else … (Python instruction)
mot_de_passe = input("Enter the password: ")
if mot_de_passe == "sesame":
print("Thank you. You may enter.")
else:
print("Sorry. Wrong password.")
• Multiple branches
if … elif … else (Python instruction)
age = int(input("Enter your age: "))
if age < 3:
print("You are a baby.")
elif age < 12:
print("You are a child.")
elif age < 18:
print("You are a teenager.")
else:
print("You are an adult.")
Remark : with elif, a condition is only tested if the previous ones are false: no need to write age >= 3. The else is optional.
III - Loops
A loop repeats the same block of instructions.
• Bounded loop: for … from … to …
The number of iterations is known in advance: a counter is incremented at each pass. In Python: for i in range(start, end, step):, or range(start, end) (step $1$), or range(end) (start $0$, step $1$).
Warning : the end value is excluded: range(0, 10, 2) gives $0, 2, 4, 6, 8$ and range(3) gives $0, 1, 2$.
for (Python instruction)
# Computing 2 to the power 3
a = 1
for compteur in range(3):
a = a * 2
print("2 to the power 3 is:", a)
# Sum of the squares of the even numbers below 10
somme_carres = 0
for i in range(0, 10, 2):
somme_carres = somme_carres + i * i
print("Sum:", somme_carres) # displays 120
• Unbounded loop: while …
A block is repeated as long as a condition is true; the test is done at the start of each pass and the number of iterations is not known in advance. In Python: while condition:.
while (Python instruction)
# The user must type a non-negative number
x = -1
while x < 0:
x = float(input("Enter a non-negative number: "))
print("The value of x is", x)
Application: threshold algorithm
A capital of $1\,000$ € is invested at $4\,\%$ a year. After how many years does it exceed $1\,500$ €?
C = 1000
n = 0
while C <= 1500:
C = C * 1.04
n = n + 1
print(n) # displays 11
Python 3: lo básico
El objetivo de este curso es implementar algoritmos con el lenguaje Python.
I - Primeras instrucciones en Python
• Comentarios
Un comentario empieza con el símbolo #: el resto de la línea se ignora al ejecutar. Facilita la comprensión del programa.
Insertar un comentario (instrucción Python)
# Esto es un comentario de una línea en Python.
• Uso de una variable
Una variable está asociada a un espacio de memoria y almacena un valor (número, cadena…). Su nombre empieza por una letra y no contiene espacios ni caracteres especiales (solo el guion bajo _). Se asigna un valor con el símbolo =.
Uso de una variable (instrucción Python)
# Se crea una variable nombre1 y se le asigna el valor 5 nombre1 = 5 nombre2 = -3.4 somme = nombre1 + nombre2 produit = nombre1 * nombre2 quotient = nombre1 / nombre2 # Potencia: nombre1 al cubo puissance3 = nombre1 ** 3 phrase = "Hello World !"
Observación : en Python, la coma decimal se escribe con un punto: $-3{,}4$ se escribe -3.4. El cociente entero se obtiene con // y el resto con % (ejemplo: 17 // 5 vale $3$ y 17 % 5 vale $2$).
• Mostrar en la consola
Para mostrar información, se usa la instrucción print.
Mostrar en la consola (instrucción Python)
# Mostrar un mensaje (con comillas)
print("Me gusta aprender Python.")
# Mostrar el contenido de una variable (sin comillas)
phrase = "Hello World !"
print(phrase)
# Combinar mensajes y variables
nom = "Pierre"
age = 16
print(nom, "tiene", age, "años.")
• Entrada por teclado
La instrucción input almacena una cadena escrita con el teclado. Para un número, se convierte con int (entero), float (decimal) o eval (cualquier expresión, por ejemplo 7/2).
Entrada por teclado (instrucción Python)
phrase = input("Escriba su nombre: ")
nombre_entier = int(input("Escriba un entero: "))
nombre_decimal = float(input("Escriba un decimal: "))
nombre_reel = eval(input("Escriba un número real: "))
II - Instrucciones condicionales
Algunas instrucciones solo se ejecutan si se cumple una condición. Los operadores de comparación $=$, $\neq$, $<$, $>$, $\leqslant$, $\geqslant$ se escriben en Python ==, !=, <, >, <=, >=.
• Si … entonces …
En Python: if condición:; el bloque siguiente se desplaza una tabulación (4 espacios): está sangrado.
Si … entonces … (instrucción Python)
mot_de_passe = input("Escriba la contraseña: ")
if mot_de_passe == "sesame":
print("Gracias. Puede entrar.")
Observación : Python distingue mayúsculas y minúsculas: Sesame y sesame son distintos.
Una condición puede combinar varias pruebas con los operadores lógicos Y (and) y O (or): «c1 Y c2» es verdadera si ambas lo son; «c1 O c2» si al menos una lo es.
and, or (instrucción Python)
nombre = float(input("Escriba un número: "))
if nombre >= 1 and nombre <= 2:
print("El número pertenece a [1;2].")
if nombre < 1 or nombre > 2:
print("El número pertenece a ]-inf;1[ U ]2;+inf[.")
• Si … entonces … si no …
Si … entonces … si no … (instrucción Python)
mot_de_passe = input("Escriba la contraseña: ")
if mot_de_passe == "sesame":
print("Gracias. Puede entrar.")
else:
print("Lo siento. Contraseña incorrecta.")
• Ramificación condicional
if … elif … else (instrucción Python)
age = int(input("Escriba su edad: "))
if age < 3:
print("Es un bebé.")
elif age < 12:
print("Es un niño.")
elif age < 18:
print("Es un adolescente.")
else:
print("Es un adulto.")
Observación : con elif, una condición solo se prueba si las anteriores son falsas: no hace falta escribir age >= 3. El else es opcional.
III - Bucles
Un bucle repite un mismo bloque de instrucciones.
• Bucle acotado: para … desde … hasta …
El número de iteraciones se conoce de antemano: un contador se incrementa en cada paso. En Python: for i in range(inicio, fin, paso):, o range(inicio, fin) (paso $1$), o range(fin) (inicio $0$, paso $1$).
Atención : el valor fin está excluido: range(0, 10, 2) da $0, 2, 4, 6, 8$ y range(3) da $0, 1, 2$.
for (instrucción Python)
# Cálculo de 2 elevado a 3
a = 1
for compteur in range(3):
a = a * 2
print("2 elevado a 3 vale:", a)
# Suma de los cuadrados de los pares menores que 10
somme_carres = 0
for i in range(0, 10, 2):
somme_carres = somme_carres + i * i
print("Suma:", somme_carres) # muestra 120
• Bucle no acotado: mientras …
Se repite un bloque mientras una condición sea verdadera; la prueba se hace al principio de cada paso y no se conoce el número de iteraciones. En Python: while condición:.
while (instrucción Python)
# El usuario debe escribir un número positivo o nulo
x = -1
while x < 0:
x = float(input("Escriba un número positivo o nulo: "))
print("El valor de x es", x)
Aplicación: algoritmo de umbral
Un capital de $1\,000$ € se invierte al $4\,\%$ anual. ¿Al cabo de cuántos años supera los $1\,500$ €?
C = 1000
n = 0
while C <= 1500:
C = C * 1.04
n = n + 1
print(n) # muestra 11