0%
Python Fundamentals for Web Development and Data Analysis

Python Fundamentals for Web Development and Data Analysis

A complete guide to mastering the basics of Python, the versatile programming language ideal for web development, data analysis, and artificial intelligence.

I

InSkillCoach

· min

Python: A Complete Guide for Beginners and Intermediate Developers

Python is one of the most popular and accessible programming languages in the world. Its clear syntax and great versatility make it an excellent choice for beginners and experienced developers alike. This guide introduces the core concepts of Python and shows you how to use them effectively in your projects.

Why Choose Python?

Python stands out for several characteristics that explain its growing popularity:

  • Clear, readable syntax: Designed to be easy to read and write
  • Versatile: Used in web development, data analysis, AI, automation, and more
  • Large community: A vast community of developers and abundant resources
  • Rich in libraries: Thousands of packages to extend its functionality
  • Interpreted: No need to compile your code, which speeds up development
  • Cross-platform: Runs on Windows, macOS, Linux, and many other systems

Installing Python

To get started with Python, you first need to install it on your system:

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

Virtual Environments

Using virtual environments is a best practice for isolating your projects’ dependencies:

# 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

Basic Syntax and Data Types

Variables and Assignment

# Variables
nom = "Alice"
age = 30
taille = 1.75
est_developpeur = True

# Affichage de variables
print(f"Je m'appelle {nom}, j'ai {age} ans.")

Fundamental Data Types

# 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")

Control Structures

Conditions

# 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")

Loops

# 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)

Functions

# 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

Object-Oriented Programming

# 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())

File Handling

# 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.")

Exception Handling

# 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."

Modules and Packages

# 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

Data Analysis

# 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)

Data Visualization

# 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()

Web Development

# 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 Best Practices

Naming Conventions

  • Variables and functions: snake_case (example: ma_variable, calculer_moyenne)
  • Classes: PascalCase (example: MaClasse, GestionnaireDeConnexion)
  • Constants: UPPER_CASE (example: PI, MAX_TAILLE)
  • Modules: snake_case (example: mon_module.py)
  • “Private” variables: _ prefix (example: _variable_interne)

Code Style (PEP 8)

  • Use 4 spaces for indentation (no tabs)
  • Limit lines to 79 characters
  • Leave 2 blank lines between top-level class and function definitions
  • Surround operators with spaces: x = 1 + 2
  • Don’t put spaces before function call parentheses: print(x)
  • Add docstrings to your functions and classes

Documentation

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)

Testing

# 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()

Conclusion

Python is a powerful, flexible language that can be used in many fields. By mastering its fundamentals, you will be able to:

  • Automate repetitive tasks
  • Analyze and visualize data
  • Build web applications
  • Develop artificial intelligence models
  • Create tools and utilities

To go further, explore Python’s many specialized libraries and get involved in the active community that continues to evolve this versatile and accessible language.

InSkillCoach

About InSkillCoach

Training and technology expert

Coach specializing in advanced technologies and AI, backed by GNeurone Inc.

Certifications:

  • AWS Certified Solutions Architect – Professional
  • Google Cloud certifications
  • Microsoft Certified: DevOps Engineer Expert
  • Certified Kubernetes Administrator (CKA)
  • CompTIA Security+
841
86

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!