NumPy is the foundational library for numerical computing in Python. It provides:
import numpy as np
# 1D array
arr1 = np.array([1, 2, 3])
# 2D array (matrix)
arr2 = np.array([[1, 2], [3, 4]])
# Special arrays
zeros = np.zeros((3, 3)) # 3x3 matrix of zeros
ones = np.ones((2, 2)) # 2x2 matrix of ones
range_arr = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
linspace = np.linspace(0, 1, 5) # 5 evenly spaced numbers between 0 and 1
print("1D Array:", arr1)
print("2D Array:\n", arr2)
print("Zeros:\n", zeros)
print("Linspace:", linspace)
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Element-wise operations
print("Addition:", a + b) # [5, 7, 9]
print("Multiplication:", a * b) # [4, 10, 18]
# Broadcasting (applying operations to mismatched shapes)
print("Array + Scalar:", a + 5) # [6, 7, 8]
# Trigonometry
angles = np.array([0, 30, 45, 60, 90]) * np.pi / 180
print("Sine:", np.sin(angles))
# Statistics
data = np.array([1, 2, 3, 4, 5])
print("Mean:", np.mean(data))
print("Standard Deviation:", np.std(data))
# Matrix operations
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print("Matrix Multiplication:\n", np.matmul(A, B))
print("Inverse of A:\n", np.linalg.inv(A))
Pandas provides DataFrames (tables) and Series (columns) for:
import pandas as pd
# Series (1D array with labels)
series = pd.Series([10, 20, 30], index=["A", "B", "C"])
# DataFrame (2D table)
data = {"Name": ["Alice", "Bob"], "Age": [25, 30]}
df = pd.DataFrame(data)
print("Series:\n", series)
print("DataFrame:\n", df)
# Filtering
print("Age > 25:\n", df[df["Age"] > 25])
# Grouping & Aggregation
sales = pd.DataFrame({
"Region": ["East", "West", "East", "West"],
"Sales": [200, 300, 150, 400]
})
print("Average Sales by Region:\n", sales.groupby("Region").mean())
df = pd.DataFrame({"A": [1, None, 3], "B": [4, 5, None]})
print("Original:\n", df)
print("Filled NA:\n", df.fillna(0)) # Replace missing values with 0
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
plt.plot(x, y, label="Line Plot")
plt.bar(x, y, label="Bar Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.show()
import seaborn as sns
tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill", data=tips)
plt.title("Bill Distribution by Day")
plt.show()
import requests
# GET request
response = requests.get("https://api.github.com")
print("Status Code:", response.status_code)
print("JSON Data:", response.json())
# POST request
data = {"key": "value"}
response = requests.post("https://httpbin.org/post", data=data)
print("POST Response:", response.json())
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, World!"
if __name__ == "__main__":
app.run(debug=True)
http://127.0.0.1:5000)django-admin startproject to create a project
import sqlite3
conn = sqlite3.connect("example.db")
cursor = conn.cursor()
# Create table
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER, name TEXT)")
# Insert data
cursor.execute("INSERT INTO users VALUES (1, 'Alice')")
# Query data
cursor.execute("SELECT * FROM users")
print(cursor.fetchall()) # [(1, 'Alice')]
conn.commit()
conn.close()
example.db)This guide covered:
Each library serves a specific purpose in Python development, from data science to web apps. 🚀