Python CheatSheet

🐍 Python Basics

# Hello World
print("Hello, World!")

💡 Tip: No semicolons, indentation defines code blocks.

📦 Variables & Data Types

age = 25
price = 99.99
name = "Maxon"
is_active = True
items = [1, 2, 3]
data = {"key": "value"}

💡 Tip: Python is dynamically typed, no need to declare variable types.

🔀 Control Flow

num = 10

if num > 5:
    print("Greater than 5")
elif num == 5:
    print("Equal to 5")
else:
    print("Less than 5")

💡 Tip: Use elif instead of multiple if blocks.

🔁 Loops

# for loop
for i in range(5):
    print(i)

# while loop
j = 0
while j < 5:
    print(j)
    j += 1

💡 Tip: Use enumerate() to loop with index.

⚙️ Functions

def greet(name):
    return f"Hello, {name}"

print(greet("Maxon"))

💡 Tip: Functions are first-class citizens in Python.

🏗️ OOP (Classes & Objects)

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hi, I'm {self.name}")

p1 = Person("Maxon", 25)
p1.greet()

💡 Tip: Use self to access instance variables.

🧬 Inheritance

class Animal:
    def sound(self):
        print("Animal sound")

class Dog(Animal):
    def sound(self):
        print("Bark")

a = Dog()
a.sound()

💡 Tip: Use super() to call parent methods.

📦 Modules

# math module
import math
print(math.sqrt(16))

# custom module
# file: mymodule.py
def add(a, b): return a + b

# file: main.py
from mymodule import add
print(add(2, 3))

💡 Tip: Use pip to install external libraries.

🚨 Exception Handling

try:
    x = 10 / 0
except ZeroDivisionError as e:
    print("Error:", e)
finally:
    print("Always runs")

💡 Tip: Use multiple except blocks for different errors.

📂 File Handling

# write to file
with open("file.txt", "w") as f:
    f.write("Hello File!")

# read file
with open("file.txt", "r") as f:
    content = f.read()
    print(content)

💡 Tip: Always use with for safe file handling.

✨ Decorators

def decorator(func):
    def wrapper():
        print("Before function")
        func()
        print("After function")
    return wrapper

@decorator
def say_hello():
    print("Hello!")

say_hello()

💡 Tip: Decorators add extra functionality to functions.

🔄 Generators

def my_gen():
    for i in range(3):
        yield i

for val in my_gen():
    print(val)

💡 Tip: Use yield to return values lazily.

⚡ List Comprehensions

nums = [1, 2, 3, 4]
squares = [n**2 for n in nums if n % 2 == 0]
print(squares)  # [4, 16]

💡 Tip: Comprehensions make code concise & faster.

⚡ Async & Await

import asyncio

async def task():
    print("Task running...")
    await asyncio.sleep(1)
    print("Task finished")

asyncio.run(task())

💡 Tip: Use async for I/O-bound tasks, not CPU-bound work.

🔢 NumPy (Numerical Computing)

import numpy as np

# Array creation
arr = np.array([1, 2, 3, 4])
print(arr)

# Zeros & Ones
zeros = np.zeros((2,2))
ones = np.ones((3,3))

# Operations
print(arr * 2)       # [2 4 6 8]
print(np.mean(arr))  # Average

💡 Tip: NumPy arrays are faster than Python lists for large data.

📊 Pandas (Data Analysis)

import pandas as pd

# Create DataFrame
data = {"Name": ["Alice", "Bob"], "Age": [25, 30]}
df = pd.DataFrame(data)

# Read CSV
df = pd.read_csv("data.csv")

# Access
print(df.head())
print(df["Name"])  # Column access

💡 Tip: Use df.info() & df.describe() to explore datasets quickly.

🌐 Flask (Web Framework)

from flask import Flask

app = Flask(__name__)

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

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

💡 Tip: Flask is lightweight, perfect for small web apps & APIs.

🏗️ Django (Web Framework)

# Install Django
# pip install django

# Create project
django-admin startproject mysite

# Run server
python manage.py runserver

# Create app
python manage.py startapp blog

💡 Tip: Django is full-featured with ORM, admin panel & authentication.

📦 Virtual Environment

# Create virtual env
python -m venv venv

# Activate
# Windows
venv\Scripts\activate
# Mac/Linux
source venv/bin/activate

# Install packages
pip install requests

💡 Tip: Always use virtual envs to isolate dependencies per project.

🌍 Requests (HTTP API)

import requests

res = requests.get("https://api.github.com")
print(res.status_code)
print(res.json())

💡 Tip: Use requests to interact with REST APIs.

🤖 Scikit-Learn (Machine Learning)

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import numpy as np

# Sample dataset
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([2, 4, 6, 8, 10])

# Split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# Train model
model = LinearRegression()
model.fit(X_train, y_train)

# Predict
print(model.predict([[6]]))  # ~12

💡 Tip: Scikit-Learn is best for quick ML models (classification, regression, clustering).

🧠 TensorFlow (Deep Learning)

import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense

# Simple Neural Network
model = Sequential([
    Dense(64, activation="relu", input_shape=(10,)),
    Dense(1, activation="linear")
])

model.compile(optimizer="adam", loss="mse")

# Train
import numpy as np
X = np.random.rand(100, 10)
y = np.random.rand(100, 1)

model.fit(X, y, epochs=5, batch_size=8)

💡 Tip: TensorFlow is for deep learning — use it for neural networks & AI projects.

📈 Data Visualization

import matplotlib.pyplot as plt
import seaborn as sns

# Line Plot
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y)
plt.show()

# Heatmap with Seaborn
import numpy as np
data = np.random.rand(5, 5)
sns.heatmap(data, annot=True)
plt.show()

💡 Tip: Visualization is key in ML/AI — use matplotlib for basic plots & seaborn for advanced ones.

📓 Jupyter Notebook

# Install Jupyter
pip install notebook

# Start notebook
jupyter notebook

# In Notebook, use magic commands:
%time    # Check execution time
%matplotlib inline  # Show plots inline

💡 Tip: Use Jupyter for ML/AI projects — best for interactive coding & visualizations.

✅ Python Best Practices & Tips

# 1. Follow PEP8 (Python Style Guide)
# Install linter: pip install flake8

def my_function(x, y):
    return x + y  # ✅ Good
def myFunc(X,Y): return X+Y  # ❌ Bad

# 2. Use Virtual Environments
python -m venv venv
source venv/bin/activate

# 3. Use List Comprehensions
nums = [x**2 for x in range(10)]

# 4. Handle Errors Safely
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print("Error:", e)

# 5. Use f-Strings for Formatting
name = "Alice"
print(f"Hello, {name}!")

# 6. Use Logging Instead of Print
import logging
logging.basicConfig(level=logging.INFO)
logging.info("App started")

# 7. Write Docstrings
def greet(name):
    """Return a greeting message for a name."""
    return f"Hello {name}"

# 8. Use Enumerate & Zip
for i, val in enumerate(["a","b","c"]):
    print(i, val)

names = ["Alice", "Bob"]
scores = [90, 85]
for n, s in zip(names, scores):
    print(n, s)

# 9. Use Context Managers
with open("file.txt", "r") as f:
    data = f.read()

# 10. Debugging with pdb
import pdb; pdb.set_trace()

💡 Tip: Writing clean, maintainable, and error-free code is more important than writing complex one-liners.

Post a Comment