أساسيات Python لتطوير الويب وتحليل البيانات
دليل شامل لإتقان أساسيات Python، لغة البرمجة متعددة الاستخدامات المثالية لتطوير الويب وتحليل البيانات والذكاء الاصطناعي.
InSkillCoach
Python: دليل شامل للمبتدئين والمستوى المتوسط
تُعد Python من أكثر لغات البرمجة شعبية وسهولة في الاستخدام حول العالم. فصياغتها الواضحة وتعدد استخداماتها يجعلانها خيارًا ممتازًا للمبتدئين والمطورين ذوي الخبرة على حد سواء. يقدم لك هذا الدليل المفاهيم الأساسية في Python وكيفية استخدامها بفعالية في مشاريعك.
لماذا نختار Python؟
تتميز Python بعدة خصائص تفسر تزايد شعبيتها:
- صياغة واضحة وسهلة القراءة: صُممت لتكون سهلة القراءة والكتابة
- متعددة الاستخدامات: تُستخدم في تطوير الويب وتحليل البيانات والذكاء الاصطناعي والأتمتة وغيرها
- مجتمع كبير: مجتمع واسع من المطورين وموارد وفيرة
- غنية بالمكتبات: آلاف الحزم (packages) لتوسيع وظائفها
- لغة مفسَّرة: لا حاجة إلى ترجمة الشيفرة (compilation)، مما يسرّع التطوير
- متعددة المنصات: تعمل على Windows وmacOS وLinux وغيرها من الأنظمة
تثبيت Python
للبدء مع Python، عليك أولًا تثبيتها على نظامك:
Windows
# Télécharger depuis https://www.python.org/downloads/
# Ou installer avec winget
winget install Python.Python.3.11
macOS
# Avec Homebrew
brew install python
# Ou télécharger depuis https://www.python.org/downloads/
Linux (Ubuntu/Debian)
# Installer Python 3
sudo apt update
sudo apt install python3 python3-pip python3-venv
البيئات الافتراضية
يُعد استخدام البيئات الافتراضية ممارسة جيدة لعزل اعتماديات مشاريعك:
# Création d'un environnement virtuel
python -m venv mon_env
# Activation de l'environnement virtuel
# Sur Windows
mon_env\Scripts\activate
# Sur macOS/Linux
source mon_env/bin/activate
# Installation de packages
pip install numpy pandas matplotlib
الصياغة الأساسية وأنواع البيانات
المتغيرات والإسناد
# Variables
nom = "Alice"
age = 30
taille = 1.75
est_developpeur = True
# Affichage de variables
print(f"Je m'appelle {nom}, j'ai {age} ans.")
أنواع البيانات الأساسية
# Chaînes de caractères (str)
texte = "Bonjour, monde !"
multiple_lignes = """Ceci est un texte
sur plusieurs lignes."""
# Nombres (int, float)
entier = 42
decimal = 3.14159
# Booléens (bool)
vrai = True
faux = False
# Vérification de type
print(type(entier)) # <class 'int'>
المجموعات (Collections)
# Listes (mutables, ordonnées)
fruits = ["pomme", "banane", "orange"]
nombres = [1, 2, 3, 4, 5]
mixte = [1, "deux", 3.0, True]
# Accès aux éléments (indexation 0)
premier_fruit = fruits[0] # pomme
dernier_fruit = fruits[-1] # orange
# Modification
fruits[1] = "fraise"
fruits.append("kiwi")
fruits.extend(["mangue", "ananas"])
fruits.remove("pomme")
# Tuples (immutables, ordonnés)
coordonnees = (10, 20)
rgb = (255, 0, 128)
# Dictionnaires (paires clé-valeur)
personne = {
"nom": "Dupont",
"prenom": "Jean",
"age": 30,
"competences": ["Python", "JavaScript", "SQL"]
}
# Accès aux valeurs
print(personne["nom"])
print(personne.get("adresse", "Non spécifiée"))
# Ensembles (éléments uniques, non ordonnés)
couleurs = {"rouge", "vert", "bleu"}
couleurs.add("jaune")
هياكل التحكم
الشروط
# If, elif, else
age = 20
if age < 18:
print("Mineur")
elif age < 21:
print("Majeur, mais pas aux USA")
else:
print("Majeur partout")
# Opérateurs de comparaison
# ==, !=, <, >, <=, >=
# Opérateurs logiques
# and, or, not
if age >= 18 and age <= 65:
print("En âge de travailler")
الحلقات التكرارية
# Boucle for
for fruit in fruits:
print(fruit)
# Range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 8, 2): # 2, 4, 6
print(i)
# Énumération
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Boucle while
compteur = 0
while compteur < 5:
print(compteur)
compteur += 1
# Break et continue
for i in range(10):
if i == 3:
continue # Passe à l'itération suivante
if i == 7:
break # Sort de la boucle
print(i)
الدوال
# Définition de fonction
def saluer(nom):
"""Cette fonction salue la personne passée en paramètre."""
return f"Bonjour, {nom} !"
# Appel de fonction
message = saluer("Bob")
print(message)
# Paramètres par défaut
def saluer_formellement(nom, titre="M./Mme"):
return f"Bonjour, {titre} {nom} !"
print(saluer_formellement("Dupont"))
print(saluer_formellement("Dupont", "Dr."))
# Arguments nommés
def calculer_prix(montant, taxe=0.2, reduction=0):
return montant * (1 + taxe) - reduction
prix = calculer_prix(100, reduction=20, taxe=0.1)
# *args et **kwargs
def info_personne(nom, *hobbies, **caracteristiques):
print(f"Nom: {nom}")
print("Hobbies:")
for hobby in hobbies:
print(f"- {hobby}")
print("Autres caractéristiques:")
for cle, valeur in caracteristiques.items():
print(f"- {cle}: {valeur}")
info_personne("Alice", "lecture", "natation", "vélo",
age=28, profession="Ingénieure", ville="Paris")
# Fonctions lambda
carre = lambda x: x * x
print(carre(5)) # 25
البرمجة كائنية التوجه
# Définition de classe
class Personne:
"""Classe représentant une personne."""
# Variable de classe
espece = "Humain"
# Constructeur
def __init__(self, nom, age):
# Attributs d'instance
self.nom = nom
self.age = age
self._adresse = None # Attribut semi-privé
# Méthode d'instance
def se_presenter(self):
return f"Je m'appelle {self.nom} et j'ai {self.age} ans."
# Property
@property
def adresse(self):
return self._adresse
@adresse.setter
def adresse(self, nouvelle_adresse):
if isinstance(nouvelle_adresse, str):
self._adresse = nouvelle_adresse
else:
raise TypeError("L'adresse doit être une chaîne de caractères")
# Méthode statique
@staticmethod
def est_majeur(age):
return age >= 18
# Méthode de classe
@classmethod
def creer_depuis_annee_naissance(cls, nom, annee_naissance):
from datetime import date
age = date.today().year - annee_naissance
return cls(nom, age)
# Création d'instances
alice = Personne("Alice", 30)
print(alice.se_presenter())
bob = Personne.creer_depuis_annee_naissance("Bob", 1990)
# Héritage
class Employe(Personne):
def __init__(self, nom, age, poste, salaire):
super().__init__(nom, age)
self.poste = poste
self.salaire = salaire
def se_presenter(self):
presentation = super().se_presenter()
return f"{presentation} Je travaille comme {self.poste}."
# Polymorphisme
personnes = [alice, Employe("Charlie", 35, "Développeur", 50000)]
for personne in personnes:
print(personne.se_presenter())
التعامل مع الملفات
# Lecture de fichier
with open("exemple.txt", "r", encoding="utf-8") as fichier:
contenu = fichier.read()
print(contenu)
# Lecture ligne par ligne
with open("exemple.txt", "r", encoding="utf-8") as fichier:
for ligne in fichier:
print(ligne.strip())
# Écriture de fichier
with open("sortie.txt", "w", encoding="utf-8") as fichier:
fichier.write("Bonjour, monde !\n")
fichier.write("Ceci est un exemple d'écriture de fichier en Python.")
# Ajout à un fichier
with open("sortie.txt", "a", encoding="utf-8") as fichier:
fichier.write("\nCette ligne est ajoutée à la fin.")
معالجة الاستثناءات
# Try-except de base
try:
nombre = int(input("Entrez un nombre: "))
resultat = 10 / nombre
print(f"10 / {nombre} = {resultat}")
except ValueError:
print("Erreur: Veuillez entrer un nombre valide.")
except ZeroDivisionError:
print("Erreur: Division par zéro impossible.")
except Exception as e:
print(f"Une erreur inattendue s'est produite: {e}")
else:
print("Aucune exception levée.")
finally:
print("Ce bloc s'exécute toujours, qu'il y ait eu une exception ou non.")
# Lever des exceptions
def verifier_age(age):
if not isinstance(age, int):
raise TypeError("L'âge doit être un nombre entier")
if age < 0:
raise ValueError("L'âge ne peut pas être négatif")
return True
# Créer ses propres exceptions
class MajesteException(Exception):
"""Exception levée quand on manque de respect à Sa Majesté."""
pass
def adresser_roi(message):
if "votre majesté" not in message.lower():
raise MajesteException("Il faut s'adresser au roi avec respect !")
return "Le roi vous écoute."
الوحدات والحزم
# Import de module
import math
racine = math.sqrt(16)
# Import spécifique
from datetime import datetime, timedelta
maintenant = datetime.now()
demain = maintenant + timedelta(days=1)
# Import avec alias
import numpy as np
tableau = np.array([1, 2, 3, 4, 5])
# Création de module
# fichier: mon_module.py
def saluer(nom):
return f"Bonjour, {nom} !"
class MaClasse:
pass
# Dans un autre fichier
from mon_module import saluer, MaClasse
المكتبات الشائعة
تحليل البيانات
# Pandas pour la manipulation de données
import pandas as pd
# Création d'un DataFrame
df = pd.DataFrame({
'Nom': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Ville': ['Paris', 'Lyon', 'Marseille']
})
# Sélection de données
personnes_paris = df[df['Ville'] == 'Paris']
# Opérations statistiques
age_moyen = df['Age'].mean()
# NumPy pour le calcul scientifique
import numpy as np
# Création d'un tableau
tableau = np.array([[1, 2, 3], [4, 5, 6]])
# Opérations mathématiques
somme = np.sum(tableau)
moyenne = np.mean(tableau)
تصور البيانات
# Matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 15, 7, 12, 9]
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-o', linewidth=2, markersize=8)
plt.title('Mon Graphique')
plt.xlabel('Axe X')
plt.ylabel('Axe Y')
plt.grid(True)
plt.savefig('graphique.png')
plt.show()
# Seaborn
import seaborn as sns
# Définir un style
sns.set_theme(style="whitegrid")
# Créer un graphique
tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill", data=tips)
plt.title('Distribution des factures par jour')
plt.show()
تطوير الويب
# Flask
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def accueil():
return render_template('index.html', titre='Mon Application Web')
@app.route('/utilisateur/<nom>')
def utilisateur(nom):
return f'Bonjour, {nom} !'
if __name__ == '__main__':
app.run(debug=True)
# Django (structure de projet)
# mysite/
# ├── manage.py
# └── mysite/
# ├── __init__.py
# ├── settings.py
# ├── urls.py
# └── wsgi.py
أفضل الممارسات في Python
اصطلاحات التسمية
- المتغيرات والدوال: snake_case (مثال:
ma_variable،calculer_moyenne) - الأصناف (Classes): PascalCase (مثال:
MaClasse،GestionnaireDeConnexion) - الثوابت: UPPER_CASE (مثال:
PI،MAX_TAILLE) - الوحدات (Modules): snake_case (مثال:
mon_module.py) - المتغيرات “الخاصة”: بادئة _ (مثال:
_variable_interne)
أسلوب الشيفرة (PEP 8)
- استخدم 4 مسافات للإزاحة (وليس علامات الجدولة)
- حدّد طول الأسطر بـ 79 حرفًا
- اترك سطرين فارغين بين تعريفات الأصناف والدوال ذات المستوى الأعلى
- أحط العوامل بمسافات:
x = 1 + 2 - لا تستخدم مسافات قبل أقواس الدوال:
print(x) - أضف docstrings إلى دوالك وأصنافك
التوثيق
def calculer_moyenne(nombres):
"""
Calcule la moyenne d'une liste de nombres.
Args:
nombres (list): Une liste de nombres (int ou float)
Returns:
float: La moyenne des nombres
Raises:
TypeError: Si l'argument n'est pas une liste
ValueError: Si la liste est vide
"""
if not isinstance(nombres, list):
raise TypeError("L'argument doit être une liste")
if not nombres:
raise ValueError("La liste ne peut pas être vide")
return sum(nombres) / len(nombres)
الاختبارات
# test_calculs.py
import unittest
from calculs import calculer_moyenne
class TestCalculs(unittest.TestCase):
def test_calculer_moyenne(self):
self.assertEqual(calculer_moyenne([1, 2, 3, 4, 5]), 3.0)
self.assertEqual(calculer_moyenne([0, 0, 0]), 0.0)
def test_calculer_moyenne_erreurs(self):
with self.assertRaises(TypeError):
calculer_moyenne("pas une liste")
with self.assertRaises(ValueError):
calculer_moyenne([])
if __name__ == '__main__':
unittest.main()
الخاتمة
Python لغة قوية ومرنة يمكن استخدامها في مجالات كثيرة. فعندما تتقن أساسياتها، ستتمكن من:
- أتمتة المهام المتكررة
- تحليل البيانات وتصويرها بيانيًا
- إنشاء تطبيقات الويب
- تطوير نماذج الذكاء الاصطناعي
- بناء الأدوات والبرامج المساعدة
وللمضي قدمًا، استكشف المكتبات المتخصصة العديدة في Python، وشارك في المجتمع النشط الذي لا يزال يطوّر هذه اللغة المتعددة الاستخدامات وسهلة التعلم.
نبذة عن InSkillCoach
خبير في التدريب والتقنيات
مدرّب متخصص في التقنيات المتقدمة والذكاء الاصطناعي، تدعمه شركة GNeurone Inc.
الشهادات:
- AWS Certified Solutions Architect – Professional
- شهادات Google Cloud
- Microsoft Certified: DevOps Engineer Expert
- Certified Kubernetes Administrator (CKA)
- CompTIA Security+
التعليقات
التعليقات مدعومة عبر GitHub Discussions
سجّل الدخول باستخدام GitHub للمشاركة في النقاش