Aller au contenu

Python - Référence du langage de programmation

*Référence Python globale pour la syntaxe, les bibliothèques et les meilleures pratiques *

Python est un langage de programmation polyvalent et de haut niveau connu pour sa lisibilité et son écosystème étendu. Cette feuille de triche complète couvre la syntaxe Python, les fonctions intégrées, les bibliothèques populaires et les meilleures pratiques pour le développement efficace de Python.

Syntaxe de base

Variables et types de données

# Variable assignment
name = "Python"
age = 30
height = 5.9
is_active = True

# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0

# Data types
string_var = "Hello World"      # str
integer_var = 42               # int
float_var = 3.14              # float
boolean_var = True            # bool
list_var = [1, 2, 3]         # list
tuple_var = (1, 2, 3)        # tuple
dict_var = \\\\{"key": "value"\\\\}   # dict
set_var = \\\\{1, 2, 3\\\\}          # set
none_var = None              # NoneType

# Type checking
type(variable)               # Get type
isinstance(variable, int)    # Check if instance of type

Chaînes

# String creation
single_quotes = 'Hello'
double_quotes = "World"
triple_quotes = """Multi-line
string content"""

# String formatting
name = "Alice"
age = 30

# f-strings (Python 3.6+)
message = f"Hello \\\\{name\\\\}, you are \\\\{age\\\\} years old"
formatted = f"Pi is approximately \\\\{3.14159:.2f\\\\}"

# .format() method
message = "Hello \\\\{\\\\}, you are \\\\{\\\\} years old".format(name, age)
message = "Hello \\\\{name\\\\}, you are \\\\{age\\\\} years old".format(name=name, age=age)

# % formatting (legacy)
message = "Hello %s, you are %d years old" % (name, age)

# String methods
text = "  Hello World  "
text.strip()                 # Remove whitespace
text.lower()                 # Convert to lowercase
text.upper()                 # Convert to uppercase
text.title()                 # Title case
text.replace("Hello", "Hi")  # Replace substring
text.split()                 # Split into list
"".join(["a", "b", "c"])    # Join list into string
text.startswith("Hello")     # Check if starts with
text.endswith("World")       # Check if ends with
text.find("World")           # Find substring position
len(text)                    # String length
```_

### Listes

```python
# List creation
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
empty = []
range_list = list(range(10))  # [0, 1, 2, ..., 9]

# List operations
numbers.append(6)            # Add to end
numbers.insert(0, 0)         # Insert at position
numbers.remove(3)            # Remove first occurrence
popped = numbers.pop()       # Remove and return last
popped = numbers.pop(0)      # Remove and return at index
numbers.extend([7, 8, 9])    # Add multiple items
numbers.clear()              # Remove all items

# List access and slicing
first = numbers[0]           # First element
last = numbers[-1]           # Last element
subset = numbers[1:4]        # Elements 1, 2, 3
every_second = numbers[::2]  # Every second element
reversed_list = numbers[::-1] # Reverse list

# List comprehensions
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
words = ["hello", "world", "python"]
lengths = [len(word) for word in words]
```_

### Dictionnaires

```python
# Dictionary creation
person = \\\\{"name": "Alice", "age": 30, "city": "New York"\\\\}
empty_dict = \\\\{\\\\}
dict_from_keys = dict.fromkeys(["a", "b", "c"], 0)

# Dictionary operations
person["email"] = "alice@email.com"  # Add/update
age = person["age"]                  # Access value
age = person.get("age", 0)          # Safe access with default
del person["city"]                   # Delete key
popped = person.pop("email")         # Remove and return
person.update(\\\\{"phone": "123-456"\\\\})  # Update multiple

# Dictionary methods
keys = person.keys()                 # Get all keys
values = person.values()             # Get all values
items = person.items()               # Get key-value pairs

# Dictionary comprehensions
squares = \\\\{x: x**2 for x in range(5)\\\\}
filtered = \\\\{k: v for k, v in person.items() if len(str(v)) > 3\\\\}

Débit de contrôle

Déclarations conditionnelles

# if/elif/else
age = 18
if age >= 18:
    print("Adult")
elif age >= 13:
    print("Teenager")
else:
    print("Child")

# Ternary operator
status = "Adult" if age >= 18 else "Minor"

# Multiple conditions
if age >= 18 and age ``< 65:
    print("Working age")

if name == "Alice" or name == "Bob":
    print("Known person")

# Membership testing
if "python" in text.lower():
    print("Contains python")

if key not in dictionary:
    print("Key not found")

Boucles

# for loops
for i in range(5):              # 0, 1, 2, 3, 4
    print(i)

for i in range(1, 6):           # 1, 2, 3, 4, 5
    print(i)

for i in range(0, 10, 2):       # 0, 2, 4, 6, 8
    print(i)

# Iterate over collections
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

# Enumerate for index and value
for index, fruit in enumerate(fruits):
    print(f"\\\{index\\\}: \\\{fruit\\\}")

# Dictionary iteration
person = \\\{"name": "Alice", "age": 30\\\}
for key in person:              # Iterate over keys
    print(key)

for value in person.values():   # Iterate over values
    print(value)

for key, value in person.items(): # Iterate over key-value pairs
    print(f"\\\{key\\\}: \\\{value\\\}")

# while loops
count = 0
while count < 5:
    print(count)
    count += 1

# Loop control
for i in range(10):
    if i == 3:
        continue    # Skip to next iteration
    if i == 7:
        break      # Exit loop
    print(i)

Fonctions

Définition des fonctions

# Basic function
def greet(name):
    return f"Hello, \\\{name\\\}!"

# Function with default parameters
def greet(name, greeting="Hello"):
    return f"\\\{greeting\\\}, \\\{name\\\}!"

# Function with multiple parameters
def calculate_area(length, width):
    return length * width

# Function with variable arguments
def sum_all(*args):
    return sum(args)

# Function with keyword arguments
def create_profile(**kwargs):
    return kwargs

# Function with mixed parameters
def process_data(data, *args, **kwargs):
    # data: required parameter
    # args: variable positional arguments
    # kwargs: variable keyword arguments
    pass

# Lambda functions (anonymous functions)
square = lambda x: x**2
add = lambda x, y: x + y
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))

Exemples de fonctions

# Recursive function
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

# Generator function
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

# Decorator function
def timer(func):
    import time
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"\\\{func.__name__\\\} took \\\{end - start:.4f\\\} seconds")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)
    return "Done"

Programmation orientée objet

Classes et objets

# Basic class
class Person:
    # Class variable
    species = "Homo sapiens"

    def __init__(self, name, age):
        # Instance variables
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, I'm \\\{self.name\\\}"

    def have_birthday(self):
        self.age += 1
        return f"Happy birthday! Now \\\{self.age\\\} years old"

# Create objects
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)

# Access attributes and methods
print(person1.name)          # Alice
print(person1.greet())       # Hello, I'm Alice
person1.have_birthday()      # Happy birthday! Now 31 years old

Héritage

# Parent class
class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species

    def make_sound(self):
        return "Some generic animal sound"

    def info(self):
        return f"\\\{self.name\\\} is a \\\{self.species\\\}"

# Child class
class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name, "Dog")  # Call parent constructor
        self.breed = breed

    def make_sound(self):  # Override parent method
        return "Woof!"

    def fetch(self):  # New method specific to Dog
        return f"\\\{self.name\\\} is fetching the ball"

# Multiple inheritance
class Flyable:
    def fly(self):
        return "Flying high!"

class Bird(Animal, Flyable):
    def __init__(self, name, species):
        super().__init__(name, species)

    def make_sound(self):
        return "Tweet!"

# Create objects
dog = Dog("Buddy", "Golden Retriever")
print(dog.make_sound())      # Woof!
print(dog.fetch())           # Buddy is fetching the ball
print(dog.info())            # Buddy is a Dog

Méthodes spéciales

class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages

    def __str__(self):  # String representation
        return f"\\\{self.title\\\} by \\\{self.author\\\}"

    def __repr__(self):  # Developer representation
        return f"Book('\\\{self.title\\\}', '\\\{self.author\\\}', \\\{self.pages\\\})"

    def __len__(self):  # Length
        return self.pages

    def __eq__(self, other):  # Equality comparison
        return (self.title == other.title and
                self.author == other.author)

    def __lt__(self, other):  # Less than comparison
        return self.pages < other.pages

    def __add__(self, other):  # Addition
        total_pages = self.pages + other.pages
        return f"Combined: \\\{total_pages\\\} pages"

book1 = Book("1984", "George Orwell", 328)
book2 = Book("Animal Farm", "George Orwell", 112)

print(str(book1))           # 1984 by George Orwell
print(len(book1))           # 328
print(book1 == book2)       # False
print(book1 >`` book2)        # True
print(book1 + book2)        # Combined: 440 pages

Gestion des fichiers

Lecture des fichiers

# Basic file reading
with open("file.txt", "r") as file:
    content = file.read()       # Read entire file

with open("file.txt", "r") as file:
    lines = file.readlines()    # Read all lines into list

with open("file.txt", "r") as file:
    for line in file:           # Read line by line
        print(line.strip())

# Reading with encoding
with open("file.txt", "r", encoding="utf-8") as file:
    content = file.read()

# Reading JSON
import json
with open("data.json", "r") as file:
    data = json.load(file)

# Reading CSV
import csv
with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Écriture des fichiers

# Basic file writing
with open("output.txt", "w") as file:
    file.write("Hello, World!")

# Writing multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as file:
    file.writelines(lines)

# Appending to file
with open("output.txt", "a") as file:
    file.write("Additional content\n")

# Writing JSON
import json
data = \\\\{"name": "Alice", "age": 30\\\\}
with open("data.json", "w") as file:
    json.dump(data, file, indent=2)

# Writing CSV
import csv
data = [["Name", "Age"], ["Alice", 30], ["Bob", 25]]
with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)

Gestion des erreurs

Essayez/sauf les blocs

# Basic exception handling
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

# Multiple exception types
try:
    value = int(input("Enter a number: "))
    result = 10 / value
except ValueError:
    print("Invalid number format!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

# Catch all exceptions
try:
    risky_operation()
except Exception as e:
    print(f"An error occurred: \\\\{e\\\\}")

# Finally block (always executes)
try:
    file = open("data.txt", "r")
    data = file.read()
except FileNotFoundError:
    print("File not found!")
finally:
    if 'file' in locals():
        file.close()

# Else block (executes if no exception)
try:
    result = 10 / 2
except ZeroDivisionError:
    print("Division by zero!")
else:
    print(f"Result: \\\\{result\\\\}")
finally:
    print("Operation completed")

# Raising exceptions
def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    if age > 150:
        raise ValueError("Age seems unrealistic")
    return age

Bibliothèques populaires

Bibliothèque standard

# datetime - Date and time handling
from datetime import datetime, date, timedelta
now = datetime.now()
today = date.today()
tomorrow = today + timedelta(days=1)
formatted = now.strftime("%Y-%m-%d %H:%M:%S")

# os - Operating system interface
import os
current_dir = os.getcwd()
os.makedirs("new_directory", exist_ok=True)
files = os.listdir(".")
os.path.join("folder", "file.txt")

# sys - System-specific parameters
import sys
sys.argv                    # Command line arguments
sys.exit()                  # Exit program
sys.path                    # Python path

# random - Random number generation
import random
random.randint(1, 10)       # Random integer
random.choice([1, 2, 3])    # Random choice from list
random.shuffle(my_list)     # Shuffle list in place

# collections - Specialized container datatypes
from collections import Counter, defaultdict, deque
counter = Counter("hello world")  # Count characters
dd = defaultdict(list)           # Dict with default values
queue = deque([1, 2, 3])         # Double-ended queue

# itertools - Iterator functions
import itertools
itertools.count(10, 2)      # Infinite counting: 10, 12, 14, ...
itertools.cycle([1, 2, 3])  # Infinite cycling: 1, 2, 3, 1, 2, 3, ...
itertools.combinations([1, 2, 3], 2)  # All 2-element combinations

Bibliothèques des sciences des données

# NumPy - Numerical computing
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
matrix = np.array([[1, 2], [3, 4]])
zeros = np.zeros((3, 3))
ones = np.ones((2, 4))
random_arr = np.random.random((3, 3))

# Pandas - Data manipulation
import pandas as pd
df = pd.DataFrame(\\\\{"A": [1, 2, 3], "B": [4, 5, 6]\\\\})
df.head()                   # First 5 rows
df.describe()               # Statistical summary
df.groupby("column").sum()  # Group by and aggregate
df.to_csv("output.csv")     # Export to CSV

# Matplotlib - Plotting
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.title("Sample Plot")
plt.show()

Développement Web

# Requests - HTTP library
import requests
response = requests.get("https://api.github.com/users/octocat")
data = response.json()
status = response.status_code

# Flask - Web framework
from flask import Flask, request, jsonify
app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, World!"

@app.route("/api/data", methods=["GET", "POST"])
def api_data():
    if request.method == "POST":
        data = request.json
        return jsonify(\\\\{"received": data\\\\})
    return jsonify(\\\\{"message": "GET request"\\\\})

if __name__ == "__main__":
    app.run(debug=True)

Meilleures pratiques

Style de code (PEP 8)

# Naming conventions
variable_name = "snake_case for variables"
CONSTANT_NAME = "UPPER_CASE for constants"
class_name = "PascalCase for classes"
function_name = "snake_case for functions"

# Line length and formatting
# Keep lines under 79 characters
long_variable_name = (some_function(arg1, arg2) +
                     another_function(arg3, arg4))

# Imports
import os
import sys
from collections import defaultdict

# Whitespace
x = 1                       # Spaces around operators
y = x + 1
my_list = [1, 2, 3]        # Spaces after commas
my_dict = \\\\{"key": "value"\\\\}

# Comments
# This is a single-line comment
"""
This is a multi-line comment
or docstring for documentation
"""

def function_with_docstring(param1, param2):
    """
    Brief description of the function.

    Args:
        param1 (str): Description of param1
        param2 (int): Description of param2

    Returns:
        bool: Description of return value
    """
    return True

Conseils de performance

# List comprehensions vs loops (faster)
# Good
squares = [x**2 for x in range(1000)]

# Less efficient
squares = []
for x in range(1000):
    squares.append(x**2)

# Use built-in functions
# Good
total = sum(numbers)
maximum = max(numbers)

# Less efficient
total = 0
for num in numbers:
    total += num

# String concatenation
# Good (for many strings)
result = "".join(string_list)

# Less efficient (for many strings)
result = ""
for s in string_list:
    result += s

# Use generators for large datasets
def large_dataset():
    for i in range(1000000):
        yield i * 2

# Memory efficient
for value in large_dataset():
    process(value)

Cette feuille de triche complète de Python couvre la syntaxe, les concepts et les bibliothèques essentiels nécessaires au développement efficace de Python. Pratiquez ces concepts avec de vrais projets pour maîtriser la programmation Python.