Python Programming — Guide Complet

Status: Basic Tags: Python Programming AI ML DataScience Created: 2026-08-09 Related: LLM, Docker, Ubuntu

Introduction

Python is a high-level, interpreted programming language known for its readability and versatility. It’s widely used in web development, data science, machine learning, and automation.


Installation & Setup

Install Python on Ubuntu

# Install Python 3 and pip
sudo apt update
sudo apt install python3 python3-pip python3-venv
 
# Verify installation
python3 --version
pip3 --version

Virtual Environments

# Create a virtual environment
python3 -m venv myproject
source myproject/bin/activate
 
# Deactivate when done
deactivate
 
# Install packages
pip install numpy pandas matplotlib

Python Basics

Variables and Data Types

# Integer
x = 10
 
# Float
y = 3.14
 
# String
name = "Alice"
 
# Boolean
is_active = True
 
# List
numbers = [1, 2, 3, 4, 5]
 
# Dictionary
person = {"name": "Alice", "age": 30}
 
# Tuple
coordinates = (10, 20)
 
# Set
unique_numbers = {1, 2, 3, 4, 5}

Control Flow

# If statement
if x > 0:
    print("Positive")
elif x < 0:
    print("Negative")
else:
    print("Zero")
 
# For loop
for i in range(5):
    print(i)
 
# While loop
count = 0
while count < 5:
    print(count)
    count += 1

Functions

def greet(name):
    """Greet someone by name"""
    return f"Hello, {name}!"
 
# Function with default parameter
def add(a, b=1):
    """Add two numbers"""
    return a + b
 
# Lambda function
square = lambda x: x ** 2

Classes and Objects

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"Hello, I'm {self.name}"
    
    def __str__(self):
        return f"Person({self.name}, {self.age})"
 
# Create instance
person = Person("Alice", 30)
print(person.greet())

Essential Libraries

NumPy — Numerical Computing

import numpy as np
 
# Create arrays
arr = np.array([1, 2, 3, 4, 5])
 
# Array operations
sum_arr = np.sum(arr)
mean_arr = np.mean(arr)
std_arr = np.std(arr)
 
# Reshape arrays
matrix = np.arange(9).reshape(3, 3)
 
# Matrix operations
product = np.dot(matrix, matrix.T)

Pandas — Data Manipulation

import pandas as pd
 
# Create DataFrame
data = {"Name": ["Alice", "Bob", "Charlie"],
        "Age": [25, 30, 35],
        "City": ["New York", "London", "Paris"]}
df = pd.DataFrame(data)
 
# Data operations
mean_age = df["Age"].mean()
filtered = df[df["Age"] > 25]
 
# Read/Write files
df.to_csv("data.csv", index=False)
df = pd.read_csv("data.csv")

Matplotlib — Data Visualization

import matplotlib.pyplot as plt
 
# Basic plot
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Simple Plot")
plt.show()
 
# Bar chart
plt.bar(["A", "B", "C"], [10, 20, 15])
plt.show()
 
# Scatter plot
plt.scatter([1, 2, 3, 4], [2, 4, 6, 8])
plt.show()

Scikit-learn — Machine Learning

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
 
# Prepare data
X = [[1, 2], [2, 3], [3, 4], [4, 5]]
y = [0, 1, 1, 0]
 
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
 
# Train model
model = LogisticRegression()
model.fit(X_train, y_train)
 
# Evaluate model
predictions = model.predict(X_test)
accuracy = accuracy_score(y_test, predictions)
print(f"Accuracy: {accuracy:.2f}")

PyTorch — Deep Learning

import torch
import torch.nn as nn
 
# Create tensor
x = torch.randn(3, 4)
y = torch.randn(3, 4)
 
# Neural network
class SimpleNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(4, 8)
        self.fc2 = nn.Linear(8, 2)
    
    def forward(self, x):
        x = torch.relu(self.fc1(x))
        return self.fc2(x)
 
# Training loop
model = SimpleNet()
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
 
# Training
for epoch in range(10):
    optimizer.zero_grad()
    output = model(x)
    loss = loss_fn(output, y.long())
    loss.backward()
    optimizer.step()
    print(f"Epoch {epoch+1}, Loss: {loss.item():.4f}")

TensorFlow/Keras — Deep Learning

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
 
# Build model
model = Sequential([
    Dense(128, activation='relu', input_shape=(784,)),
    Dropout(0.2),
    Dense(64, activation='relu'),
    Dropout(0.2),
    Dense(10, activation='softmax')
])
 
# Compile model
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
 
# Train model
model.fit(X_train, y_train, epochs=10, batch_size=32)
 
# Evaluate model
loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test accuracy: {accuracy:.4f}")

Working with Data

File I/O

# Read text file
with open("data.txt", "r") as f:
    content = f.read()
 
# Write text file
with open("output.txt", "w") as f:
    f.write("Hello, World!")
 
# Read CSV
import csv
with open("data.csv", "r") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row)
 
# Write CSV
with open("output.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Age"])
    writer.writerow(["Alice", 25])

APIs and Web Requests

import requests
 
# GET request
response = requests.get("https://api.example.com/data")
data = response.json()
 
# POST request
response = requests.post("https://api.example.com/data", 
                        json={"key": "value"})
 
# Handle response
if response.status_code == 200:
    print(data)
else:
    print(f"Error: {response.status_code}")

JSON Handling

import json
 
# Parse JSON
json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)
 
# Create JSON
data = {"name": "Bob", "age": 25}
json_string = json.dumps(data, indent=2)

Best Practices

Code Organization

# Use functions for reusable code
def process_data(data):
    """Process and clean data"""
    return data.dropna()
 
# Use classes for complex objects
class DataProcessor:
    def __init__(self, filepath):
        self.filepath = filepath
        self.data = None
    
    def load(self):
        self.data = pd.read_csv(self.filepath)
        return self
    
    def process(self):
        self.data = self.data.dropna()
        return self
    
    def save(self, output_path):
        self.data.to_csv(output_path, index=False)
 
# Use main block
if __name__ == "__main__":
    processor = DataProcessor("data.csv")
    processor.load().process().save("cleaned_data.csv")

Error Handling

try:
    # Try to execute code
    result = 10 / 0
except ZeroDivisionError:
    # Handle specific error
    print("Cannot divide by zero")
except Exception as e:
    # Handle general error
    print(f"Error: {e}")
finally:
    # Always execute
    print("Done")

Testing

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
 
def test_greet():
    assert greet("Alice") == "Hello, Alice!"
    assert greet("") == "Hello, !"
 
if __name__ == "__main__":
    test_add()
    test_greet()
    print("All tests passed!")

Advanced Topics

Decorators

import functools
 
def timing_decorator(func):
    """Decorator to measure function execution time"""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} took {end_time - start_time:.4f} seconds")
        return result
    return wrapper
 
@timing_decorator
def slow_function():
    time.sleep(1)

Context Managers

class DatabaseConnection:
    def __init__(self, connection_string):
        self.connection_string = connection_string
    
    def __enter__(self):
        # Establish connection
        self.connection = connect(self.connection_string)
        return self.connection
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        # Close connection
        self.connection.close()
 
# Use context manager
with DatabaseConnection("db://localhost/mydb") as conn:
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM users")
    results = cursor.fetchall()

Generators

def fibonacci():
    """Generate Fibonacci sequence"""
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b
 
# Use generator
fib = fibonacci()
for i in range(10):
    print(next(fib))

Resources

Documentation

Learning Resources

Tools