Python — Documentation complète

Langage + exemples + bonnes pratiques

Python — c’est quoi ?

Python est un langage de programmation polyvalent, simple à lire, utilisé partout : web, data, automation, IA, jeux, systèmes, etc. Il est souvent recommandé pour apprendre la programmation car sa syntaxe est claire.

Pourquoi Python est partout ?

Car il est rapide à écrire, possède un énorme écosystème, est utilisé par des entreprises, des chercheurs, des développeurs, et des hobbyistes.

# Types basiques
a = 10           # int
b = 3.14         # float
c = "Bonjour"    # str
d = True         # bool
e = None         # null

# Liste
lst = [1, 2, 3]

# Tuple
tpl = (1, 2, 3)

# Dictionnaire
dic = {"nom":"Ali", "age":11}
        
a = 5
if a > 0:
    print("positif")
elif a == 0:
    print("nul")
else:
    print("négatif")
        
# boucle for
for i in range(5):
    print(i)

# boucle while
i = 0
while i < 5:
    print(i)
    i += 1
        
def add(a, b):
    return a + b

print(add(2, 3))
        
# Lire un fichier
with open("file.txt", "r") as f:
    text = f.read()

# Écrire un fichier
with open("file.txt", "w") as f:
    f.write("Hello")
        
# installer un module
pip install requests

# utiliser un module
import requests
res = requests.get("https://example.com")
print(res.status_code)
        
class Personne:
    def __init__(self, nom, age):
        self.nom = nom
        self.age = age

    def salut(self):
        return f"Bonjour {self.nom}"

p = Personne("Ali", 11)
print(p.salut())
        
# 1) Vérifier un palindrome
def palindrome(s):
    return s == s[::-1]

print(palindrome("radar"))

# 2) Compter mots
text = "Python est partout"
print(len(text.split()))

# 3) Calculer factorielle
def fact(n):
    if n == 0: return 1
    return n * fact(n-1)

print(fact(5))
        

Tkinter — GUI complète

Fenêtres, boutons, layout, événements, projets

Tkinter est le module standard de Python pour créer des interfaces graphiques (GUI). Il est installé automatiquement avec Python.

Installation

Tkinter est déjà installé avec Python. Si ce n’est pas le cas, il faut installer le paquet système.

Concepts clés

- Widgets : boutons, labels, entrées
- Layout : pack, grid, place
- Événements : clics, clavier
- Fenêtres : Tk(), Toplevel()

import tkinter as tk

fen = tk.Tk()
fen.title("Fenêtre Tkinter")
fen.geometry("400x300")
fen.mainloop()
        
import tkinter as tk

fen = tk.Tk()

lbl = tk.Label(fen, text="Bonjour")
lbl.pack()

ent = tk.Entry(fen)
ent.pack()

def clic():
    print("Texte:", ent.get())

btn = tk.Button(fen, text="Afficher", command=clic)
btn.pack()

fen.mainloop()
        
# pack
btn.pack(side="left")

# grid
tk.Label(fen, text="Nom").grid(row=0, column=0)
tk.Entry(fen).grid(row=0, column=1)

# place
btn.place(x=50, y=50)
        
# Checkbox
var = tk.IntVar()
cb = tk.Checkbutton(fen, text="Option", variable=var)
cb.pack()

# Radiobutton
r = tk.IntVar()
tk.Radiobutton(fen, text="A", variable=r, value=1).pack()
tk.Radiobutton(fen, text="B", variable=r, value=2).pack()

# Listbox
lb = tk.Listbox(fen)
lb.insert(1, "Option 1")
lb.insert(2, "Option 2")
lb.pack()
        
import tkinter as tk

def add():
    a = float(ent_a.get())
    b = float(ent_b.get())
    res = a + b
    lbl_res.config(text=f"Résultat: {res}")

fen = tk.Tk()
fen.title("Calculatrice")

tk.Label(fen, text="A").pack()
ent_a = tk.Entry(fen)
ent_a.pack()

tk.Label(fen, text="B").pack()
ent_b = tk.Entry(fen)
ent_b.pack()

tk.Button(fen, text="Addition", command=add).pack()
lbl_res = tk.Label(fen, text="Résultat:")
lbl_res.pack()

fen.mainloop()
        
Projets possibles :
- Mini éditeur de texte
- Gestionnaire de tâches
- Convertisseur d’unités
- Lecteur de musique
- Interface pour un script Python (API)
- Jeu simple (tic-tac-toe)
        

Gradio — Interface web rapide

Serveur web local + partage instantané

Gradio permet de créer une interface web en 2 minutes pour n’importe quel script Python. Idéal pour montrer un projet ou une IA.

Installation

pip install gradio

Concept

Gradio crée un serveur local, puis affiche une URL comme http://127.0.0.1:7860

import gradio as gr

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

demo = gr.Interface(fn=add, inputs=["number", "number"], outputs="number")
demo.launch()
        
import gradio as gr

def salut(nom):
    return "Bonjour " + nom

demo = gr.Interface(fn=salut, inputs="text", outputs="text")
demo.launch()
        
import gradio as gr
from PIL import Image

def miroir(img):
    return img.transpose(Image.FLIP_LEFT_RIGHT)

demo = gr.Interface(fn=miroir, inputs="image", outputs="image")
demo.launch()
        
import gradio as gr

def traiter(nom, age, choix):
    return f"Nom: {nom}, Age: {age}, Choix: {choix}"

demo = gr.Interface(
    fn=traiter,
    inputs=[
        gr.Textbox(label="Nom"),
        gr.Slider(0, 100, label="Age"),
        gr.Dropdown(["Option 1", "Option 2"], label="Choix")
    ],
    outputs="text"
)

demo.launch()
        
demo.launch(share=True)
        

Ça génère une URL publique accessible partout.

Hébergement sur vieux PC (Windows / Mac / Linux)

Guide complet

Tu peux héberger un site HTML sur un vieux PC. Il suffit d’installer un serveur web ou d’utiliser Python pour servir les fichiers.

Matériel minimum recommandé

- CPU : 1 cœur minimum
- RAM : 512MB minimum (1GB conseillé)
- Stockage : 2GB minimum
- Connexion : 1Mbps minimum (plus c’est mieux)

Ce qu’il te faut

- Une IP locale fixe (ou config DHCP)
- Un port ouvert (80 ou 8000)
- Un routeur configuré si accès extérieur
- Un DNS (optionnel)


# Ouvre le fichier index.html dans ton navigateur
# Exemple : C:\site\index.html
        

Tu peux déjà ouvrir ton site en local sans serveur.


cd /chemin/du/dossier
python -m http.server 8000
        

Accès : http://localhost:8000

Windows (XP / Vista / 7 / 8 / 8.1 / 10)

Options & conseils

Windows XP

XP est trop vieux pour un serveur sécurisé moderne. Le mieux est d’installer Linux léger à la place.

Windows Vista / 7 / 8 / 8.1

Tu peux installer XAMPP ou WampServer, ou utiliser Python pour un site simple.

Windows 10 (Home / LTSC)

Idéal pour un petit serveur local. Tu peux utiliser :
- XAMPP / WampServer
- Nginx
- Python


1) Installer XAMPP
2) Mettre les fichiers dans C:\xampp\htdocs
3) Démarrer Apache
4) Ouvrir http://localhost
        

Mac (Mavericks → High Sierra)

Apache / MAMP / Python

Apache (souvent déjà installé)

Place tes fichiers dans /Library/WebServer/Documents

MAMP

Simple à utiliser : serveur Apache + PHP + MySQL.

Python

Le plus simple pour un site HTML.


cd /chemin/du/dossier
python3 -m http.server 8000
        

Linux (Ubuntu / Arch / Fedora)

Nginx + Python

Ubuntu

sudo apt install nginx

Arch

sudo pacman -S nginx

Fedora

sudo dnf install nginx


sudo apt update
sudo apt install nginx
sudo systemctl start nginx
sudo systemctl enable nginx
# fichiers HTML dans /var/www/html