Back-end · formation gratuite
Python Training
Learn Python, the versatile and powerful programming language
- Débutant
- 12 chapitres
- Exemples de code
- 100 % gratuit
Introduction to Python
Python is a high-level, interpreted, and versatile programming language created by Guido van Rossum and first published in 1991. Python is now one of the most popular languages in the world, used in many fields: web development, data science, artificial intelligence, automation, and much more.
🐍 What is Python?
Python is an interpreted and object-oriented programming language. Unlike compiled languages like C++ or Java, Python executes code line by line, making it easier to debug and test. Its simple and readable syntax makes it ideal for both beginners and experts.
💡 Why is Python so popular?
- Simple and readable syntax - Python code looks almost like English, making it easy to learn and understand
- Versatile - Used for web (Django, Flask), data science (Pandas, NumPy), AI (TensorFlow, PyTorch), automation
- Extensive standard library - Thousands of modules available for almost every need
- Active community - Millions of developers worldwide, comprehensive documentation, numerous learning resources
- Open-source and free - No licensing costs, cross-platform (Windows, Linux, macOS)
- Multi-paradigm - Supports procedural, object-oriented, and functional programming
🚀 Why learn Python?
Python is an excellent choice to start programming for several reasons:
- ✅ Easy to learn - Clear and intuitive syntax, perfect for beginners. The learning curve is gentle compared to other languages
- ✅ Versatile - Web development (Django, Flask), data science (Pandas, NumPy), AI (TensorFlow, PyTorch), automation, system scripts
- ✅ Highly in demand - One of the most sought-after languages in the job market. Used by Google, Facebook, Netflix, Instagram, Spotify
- ✅ Free and Open-Source - No cost, cross-platform, active community
- ✅ Vast ecosystem - Thousands of libraries available via pip (Python package manager)
- ✅ Large community - Abundant support and resources, active forums, free tutorials
- ✅ Rapid development - Allows quick development of prototypes and applications
📋 Prerequisites for learning Python
Python is so simple that you can start without any prior experience! However, having basic knowledge in:
- ✅ Basic computing - Know how to use a computer, create and edit files
- ✅ Logic - Understanding basic concepts (variables, conditions, loops) is useful but not required, you will learn them with Python
💡 Important note: Python is installed by default on Linux and macOS. For Windows, you can download Python from python.org. You can also use an IDE like PyCharm, VS Code, or simply the Python command-line interpreter. To test quickly, you can use online environments like Repl.it or Python.org/shell.
🎯 Python Use Cases
Python is used in many fields:
- Web development - Django, Flask to create websites and REST APIs. Modern and powerful frameworks
- Data Science - Data analysis, visualization with Pandas, NumPy, Matplotlib. Widely used in finance and research
- Artificial Intelligence - Machine Learning, Deep Learning with TensorFlow, PyTorch, Scikit-learn
- Automation - Scripts to automate repetitive tasks, file processing, web scraping
- Desktop applications - Tkinter, PyQt to create cross-platform graphical interfaces
- Game development - Pygame to create 2D video games
- Web scraping - BeautifulSoup, Scrapy to extract data from websites
- Scientific computing - NumPy, SciPy for mathematical and scientific calculations
📝 Basic Syntax
Python syntax is simple and readable. Python uses indentation (spaces or tabs) to define code blocks, unlike other languages that use braces {} or keywords like begin/end.
# Premier programme Python
print("Bonjour, monde !")
# Variables
nom = "NiangProgrammeur"
age = 25
# F-strings pour formater les chaînes (Python 3.6+)
print(f"Je m'appelle {nom} et j'ai {age} ans")
# Opérations simples
resultat = 10 + 5
print(f"10 + 5 = {resultat}")
💡 Important points about Python syntax:
- Python is indentation-sensitive - Use 4 spaces (recommended by PEP 8) or tabs consistently. Indentation defines code blocks
- Comments start with
#for a line, or"""for multiple lines (docstrings) - No need for semicolons at the end of lines (unlike C, Java, PHP)
- Strings can use single quotes
'or double quotes". F-strings (f"...") allow interpolation - Colons
:mark the start of a block (after if, for, def, class, etc.) - PEP 8 is the official style guide for writing readable Python code
🔍 Detailed syntax example
Here is a complete example showing several aspects of Python syntax:
# Définition d'une fonction
def calculer_moyenne(nombres):
"""Calcule la moyenne d'une liste de nombres."""
if len(nombres) == 0:
return 0
somme = sum(nombres)
moyenne = somme / len(nombres)
return moyenne
# Utilisation
notes = [15, 18, 12, 20, 16]
moyenne = calculer_moyenne(notes)
print(f"La moyenne est : {moyenne}")
🔤 Variables
In Python, variables are created simply by assigning them a value. You do not need to declare the type of variable explicitly. Python is a dynamically typed language, meaning the type is determined automatically at runtime.
# Déclaration de variables
nom = "Python" # String (chaîne de caractères)
age = 30 # Integer (entier)
prix = 19.99 # Float (nombre décimal)
est_actif = True # Boolean (booléen)
valeur_nulle = None # NoneType (valeur nulle)
# Affichage
print(nom)
print(age)
print(prix)
print(est_actif)
print(valeur_nulle)
# Réassignation (changement de type)
variable = 10
print(type(variable)) #
variable = "Dix"
print(type(variable)) #
# Noms de variables valides
nom_utilisateur = "Bassirou"
age_utilisateur = 25
_privé = "variable privée"
CONSTANTE = 3.14159 # Convention pour les constantes
📌 Rules for variable names:
- Must start with a letter or underscore
_ - Can contain letters, numbers, and underscores
- Cannot contain spaces (use
_instead) - Are case-sensitive (
age≠Age) - Cannot be Python keywords (
if,for,def, etc.) - Convention: use
snake_casefor variables (PEP 8)
📊 Data Types
Python has several built-in data types. Here are the main ones:
# Types de base (scalaires)
texte = "Hello" # str (string)
nombre = 42 # int (integer)
decimal = 3.14 # float (floating point)
booleen = True # bool (boolean)
valeur_nulle = None # NoneType
# Collections (structures de données)
liste = [1, 2, 3, 4, 5] # list (liste ordonnée, modifiable)
tuple = (1, 2, 3) # tuple (liste ordonnée, immuable)
dictionnaire = {"nom": "Python", "age": 30} # dict (paires clé-valeur)
ensemble = {1, 2, 3, 4} # set (ensemble unique, non ordonné)
# Vérifier le type
print(type(texte)) #
print(type(nombre)) #
print(type(liste)) #
print(type(dictionnaire)) #
# Conversion de types
age_str = str(25) # Convertir en string
age_int = int("25") # Convertir en entier
prix_float = float("19.99") # Convertir en décimal
📚 Python Data Types:
- str - Character strings (text)
- int - Integers (positive, negative, zero)
- float - Decimal numbers (floating point)
- bool - Booleans (True or False)
- list - Ordered and modifiable lists
- tuple - Ordered and immutable tuples
- dict - Dictionaries (key-value pairs)
- set - Sets (unique elements, unordered)
- NoneType - Type for the None value (equivalent to null)
🔢 Operators
Python supports arithmetic, comparison, logical, assignment, and identity operators:
# Opérateurs arithmétiques
a = 10
b = 3
print(a + b) # Addition: 13
print(a - b) # Soustraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.3333333333333335
print(a // b) # Division entière: 3
print(a % b) # Modulo (reste): 1
print(a ** b) # Puissance: 1000
# Opérateurs de comparaison
print(a > b) # True (supérieur à)
print(a < b) # False (inférieur à)
print(a >= b) # True (supérieur ou égal)
print(a <= b) # False (inférieur ou égal)
print(a == b) # False (égalité)
print(a != b) # True (différent)
# Opérateurs logiques
x = True
y = False
print(x and y) # False (ET logique)
print(x or y) # True (OU logique)
print(not x) # False (NON logique)
# Opérateurs d'assignation
c = 5
c += 3 # Équivalent à c = c + 3 (c devient 8)
c -= 2 # Équivalent à c = c - 2 (c devient 6)
c *= 2 # Équivalent à c = c * 2 (c devient 12)
c /= 3 # Équivalent à c = c / 3 (c devient 4.0)
# Opérateurs d'identité
liste1 = [1, 2, 3]
liste2 = [1, 2, 3]
liste3 = liste1
print(liste1 is liste2) # False (objets différents)
print(liste1 is liste3) # True (même objet)
print(liste1 == liste2) # True (valeurs égales)
🔀 Conditional Structures
Python uses if, elif (else if) and else for conditions. Indentation is crucial for defining code blocks.
# Structure if simple
age = 20
if age >= 18:
print("Vous êtes majeur")
else:
print("Vous êtes mineur")
# Structure if/elif/else
age = 15
if age >= 18:
print("Vous êtes majeur")
print("Vous pouvez voter")
elif age >= 13:
print("Vous êtes adolescent")
elif age >= 6:
print("Vous êtes enfant")
else:
print("Vous êtes un bébé")
# Conditions multiples
note = 85
if note >= 90:
mention = "Excellent"
elif note >= 80:
mention = "Très bien"
elif note >= 70:
mention = "Bien"
elif note >= 60:
mention = "Assez bien"
else:
mention = "Insuffisant"
print(f"Votre mention : {mention}")
# Opérateur ternaire (expression conditionnelle)
age = 20
statut = "Majeur" if age >= 18 else "Mineur"
print(statut)
# Conditions avec and/or
age = 25
permis = True
if age >= 18 and permis:
print("Vous pouvez conduire")
else:
print("Vous ne pouvez pas conduire")
🔄 Loops
Python offers two types of loops: for (to iterate over a sequence) and while (to repeat as long as a condition is true):
# Boucle for avec range()
for i in range(5):
print(i) # Affiche 0, 1, 2, 3, 4
# range() avec début et fin
for i in range(1, 6):
print(i) # Affiche 1, 2, 3, 4, 5
# range() avec pas
for i in range(0, 10, 2):
print(i) # Affiche 0, 2, 4, 6, 8
# Boucle for avec liste
fruits = ["pomme", "banane", "orange"]
for fruit in fruits:
print(f"J'aime les {fruit}")
# Boucle for avec index (enumerate)
fruits = ["pomme", "banane", "orange"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Boucle while
compteur = 0
while compteur < 5:
print(compteur)
compteur += 1
# Boucle while avec break
compteur = 0
while True:
print(compteur)
compteur += 1
if compteur >= 5:
break # Sortir de la boucle
# continue (passer à l'itération suivante)
for i in range(10):
if i % 2 == 0: # Si i est pair
continue # Passer au suivant
print(i) # Affiche seulement les impairs: 1, 3, 5, 7, 9
# Boucle for avec else
for i in range(5):
print(i)
else:
print("Boucle terminée") # Exécuté si la boucle se termine normalement
⚙️ Functions
Functions allow code reuse. In Python, we define a function with def. Functions can take parameters and return values with return.
# Fonction simple (sans paramètres)
def dire_bonjour():
print("Bonjour !")
dire_bonjour() # Appel de la fonction
# Fonction avec paramètres
def saluer(nom):
return f"Bonjour, {nom} !"
message = saluer("Python")
print(message) # "Bonjour, Python !"
# Fonction avec plusieurs paramètres
def additionner(a, b):
return a + b
resultat = additionner(5, 3)
print(resultat) # 8
# Fonction avec paramètres par défaut
def saluer_personne(nom, message="Bonjour"):
return f"{message}, {nom} !"
print(saluer_personne("Bassirou")) # "Bonjour, Bassirou !"
print(saluer_personne("Bassirou", "Salut")) # "Salut, Bassirou !"
# Fonction avec arguments nommés
def creer_personne(nom, age, ville="Dakar"):
return f"{nom}, {age} ans, habite à {ville}"
print(creer_personne("Bassirou", 25))
print(creer_personne(age=25, nom="Bassirou", ville="Thiès"))
# Fonction avec *args (arguments variables)
def additionner_nombres(*args):
return sum(args)
print(additionner_nombres(1, 2, 3, 4, 5)) # 15
# Fonction avec **kwargs (arguments nommés variables)
def afficher_info(**kwargs):
for cle, valeur in kwargs.items():
print(f"{cle}: {valeur}")
afficher_info(nom="Bassirou", age=25, ville="Dakar")
# Fonction lambda (fonction anonyme)
carre = lambda x: x ** 2
print(carre(5)) # 25
# Utilisation de lambda avec map()
nombres = [1, 2, 3, 4, 5]
carres = list(map(lambda x: x ** 2, nombres))
print(carres) # [1, 4, 9, 16, 25]
📋 Lists and Dictionaries
Lists and dictionaries are very useful data structures in Python. Lists are ordered and modifiable, dictionaries store key-value pairs.
# ========== LISTES ==========
# Création de listes
nombres = [1, 2, 3, 4, 5]
fruits = ["pomme", "banane", "orange"]
liste_mixte = [1, "deux", 3.0, True]
# Accès aux éléments (index commence à 0)
print(fruits[0]) # "pomme" (premier élément)
print(fruits[-1]) # "orange" (dernier élément)
# Modification
fruits[1] = "mangue" # Remplacer "banane" par "mangue"
# Méthodes des listes
fruits.append("kiwi") # Ajouter à la fin
fruits.insert(1, "ananas") # Insérer à l'index 1
fruits.remove("pomme") # Supprimer un élément
fruits.pop() # Supprimer le dernier élément
fruits.pop(0) # Supprimer l'élément à l'index 0
# Autres méthodes utiles
print(len(fruits)) # Longueur de la liste
print(fruits.count("banane")) # Compter les occurrences
fruits.sort() # Trier la liste
fruits.reverse() # Inverser la liste
# Slicing (tranches)
nombres = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nombres[2:5]) # [2, 3, 4] (de l'index 2 à 4)
print(nombres[:3]) # [0, 1, 2] (du début à l'index 2)
print(nombres[3:]) # [3, 4, 5, 6, 7, 8, 9] (de l'index 3 à la fin)
print(nombres[::2]) # [0, 2, 4, 6, 8] (tous les 2 éléments)
# ========== DICTIONNAIRES ==========
# Création de dictionnaires
personne = {
"nom": "Bassirou",
"age": 25,
"ville": "Dakar"
}
# Accès aux valeurs
print(personne["nom"]) # "Bassirou"
print(personne.get("age")) # 25 (méthode get() plus sûre)
print(personne.get("email", "Non renseigné")) # Valeur par défaut
# Modification et ajout
personne["age"] = 26 # Modifier
personne["email"] = "bassirou@example.com" # Ajouter
# Méthodes des dictionnaires
print(personne.keys()) # Toutes les clés
print(personne.values()) # Toutes les valeurs
print(personne.items()) # Toutes les paires clé-valeur
# Parcourir un dictionnaire
for cle, valeur in personne.items():
print(f"{cle}: {valeur}")
# Supprimer
del personne["email"] # Supprimer une clé
personne.pop("ville") # Supprimer et retourner la valeur
📦 Modules
Python allows importing modules to extend its functionality. A module is a file containing functions, classes, and variables that you can reuse.
# Importer un module complet
import math
print(math.sqrt(16)) # 4.0 (racine carrée)
print(math.pi) # 3.141592653589793
print(math.cos(0)) # 1.0
# Importer avec un alias
import datetime as dt
maintenant = dt.datetime.now()
print(maintenant)
# Importer des fonctions spécifiques
from math import sqrt, pi
print(sqrt(25)) # 5.0
print(pi) # 3.141592653589793
# Importer tout d'un module (non recommandé)
from math import *
print(sin(0)) # 0.0
# Modules standards utiles
import random
print(random.randint(1, 100)) # Nombre aléatoire entre 1 et 100
import os
print(os.getcwd()) # Répertoire courant
import sys
print(sys.version) # Version de Python
# Créer son propre module
# Créer un fichier mon_module.py avec :
# def ma_fonction():
# return "Hello from module"
#
# Puis l'importer :
# import mon_module
# print(mon_module.ma_fonction())
🏗️ Object-Oriented Programming
Python supports object-oriented programming (OOP). A class is a template for creating objects. Objects have attributes (data) and methods (functions).
# Définir une classe
class Personne:
# Constructeur (méthode spéciale __init__)
def __init__(self, nom, age):
self.nom = nom # Attribut d'instance
self.age = age
# Méthode d'instance
def se_presenter(self):
return f"Je m'appelle {self.nom} et j'ai {self.age} ans"
def avoir_ans(self, annees):
self.age += annees
return f"Dans {annees} ans, j'aurai {self.age} ans"
# Créer des objets (instances)
personne1 = Personne("Bassirou", 25)
personne2 = Personne("Aminata", 30)
# Utiliser les méthodes
print(personne1.se_presenter())
print(personne2.se_presenter())
print(personne1.avoir_ans(5))
# Accéder aux attributs
print(personne1.nom)
print(personne1.age)
# Classe avec attributs de classe
class Voiture:
# Attribut de classe (partagé par toutes les instances)
nombre_voitures = 0
def __init__(self, marque, modele):
self.marque = marque
self.modele = modele
Voiture.nombre_voitures += 1
def __str__(self):
return f"{self.marque} {self.modele}"
voiture1 = Voiture("Toyota", "Corolla")
voiture2 = Voiture("Honda", "Civic")
print(f"Nombre de voitures créées : {Voiture.nombre_voitures}")
# Héritage
class Etudiant(Personne):
def __init__(self, nom, age, ecole):
super().__init__(nom, age) # Appeler le constructeur parent
self.ecole = ecole
def etudier(self):
return f"{self.nom} étudie à {self.ecole}"
etudiant = Etudiant("Bassirou", 25, "UCAD")
print(etudiant.se_presenter()) # Méthode héritée
print(etudiant.etudier()) # Méthode spécifique
📁 File Handling
Python allows reading and writing files easily. It is recommended to use with to ensure automatic file closure.
# Écrire dans un fichier (mode 'w' = write)
with open("fichier.txt", "w", encoding="utf-8") as f:
f.write("Bonjour Python !\n")
f.write("Ceci est la deuxième ligne\n")
# Lire un fichier (mode 'r' = read)
with open("fichier.txt", "r", encoding="utf-8") as f:
contenu = f.read()
print(contenu)
# Lire ligne par ligne
with open("fichier.txt", "r", encoding="utf-8") as f:
for ligne in f:
print(ligne.strip()) # strip() enlève les sauts de ligne
# Lire toutes les lignes dans une liste
with open("fichier.txt", "r", encoding="utf-8") as f:
lignes = f.readlines()
print(lignes)
# Ajouter à un fichier (mode 'a' = append)
with open("fichier.txt", "a", encoding="utf-8") as f:
f.write("Nouvelle ligne ajoutée\n")
# Modes de fichier
# 'r' - Lecture (défaut)
# 'w' - Écriture (écrase le fichier existant)
# 'a' - Ajout (ajoute à la fin)
# 'x' - Création exclusive (erreur si existe)
# 'b' - Mode binaire (rb, wb)
# 't' - Mode texte (défaut, rt, wt)
# '+' - Lecture et écriture (r+, w+, a+)
# Gestion d'erreurs
try:
with open("fichier_inexistant.txt", "r") as f:
contenu = f.read()
except FileNotFoundError:
print("Le fichier n'existe pas")
except PermissionError:
print("Permission refusée")
except Exception as e:
print(f"Erreur : {e}")
💡 Best practice: Always use with to open files. This ensures the file will be closed automatically even in case of error. This is the recommended method in Python and avoids resource leaks!
🎓 Next Steps
Congratulations! You now have a solid foundation in Python.
✅ What you learned:
- Python syntax and variables
- Data types (str, int, float, bool, list, dict, tuple, set)
- Operators (arithmetic, comparison, logical)
- Conditional structures (if, elif, else)
- Loops (for and while)
- Functions (definition, parameters, return, lambda)
- Lists and dictionaries (methods, slicing)
- Modules (import, creation)
- Object-Oriented Programming (classes, objects, inheritance)
- File handling (reading, writing, error handling)
🚀 To go further:
- List comprehensions - Concise syntax for creating lists
- Exception handling - try/except to handle errors
- Packages and pip - Install external libraries
- Web development - Django or Flask to create websites
- Data Science - Pandas, NumPy for data analysis
- Artificial Intelligence - TensorFlow, PyTorch for Machine Learning