Python logo
Python Cheatsheet
25 of 25 code examples
.py
Variables
Variable declarations
Basics
name = "Alice"      # String
age = 30           # Integer  
height = 5.6       # Float
is_student = True  # Boolean
data = None        # None
Operators
Common operators
Basics
# Arithmetic
print(10 + 5)     # 15
print(10 ** 2)    # 100
print(10 // 3)    # 3

# Comparison
print(5 > 3)      # True
print(5 == '5')   # False

# Logical
print(True and False)  # False
print(True or False)   # True
Conditionals
If/else statements
Basics
# If/elif/else
if age >= 18:
    print("Adult")
elif age >= 13:
    print("Teen") 
else:
    print("Child")
Loops
For and while loops
Basics
# For loop
for i in range(3):
    print(i)

for fruit in ["apple", "banana"]:
    print(fruit)

# While loop
count = 0
while count < 3:
    print(count)
    count += 1
Functions
Function definitions
Functions
# Basic function
def greet(name):
    return f"Hello {name}!"

# Default parameters
def create_user(name, age=18):
    return {"name": name, "age": age}

# Lambda
square = lambda x: x ** 2
Lists
List operations
Data Structures
# List creation
numbers = [1, 2, 3, 4]
fruits = ["apple", "banana"]

# List methods
fruits.append("orange")    # Add to end
fruits.pop()              # Remove last
fruits.insert(0, "kiwi")  # Insert at index

# Slicing
print(numbers[1:3])       # [2, 3]
print(numbers[::-1])      # Reverse
List Comprehensions
Compact list creation
Data Structures
# Basic comprehension
squares = [x**2 for x in range(5)]
# [0, 1, 4, 9, 16]

# With condition
evens = [x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]

# Nested
matrix = [[i*j for j in range(3)] for i in range(3)]
# [[0,0,0], [0,1,2], [0,2,4]]
Dictionaries
Key-value pairs
Data Structures
# Dictionary creation
person = {
    "name": "Alice",
    "age": 30,
    "city": "NYC"
}

# Access
print(person["name"])     # "Alice"
print(person.get("age"))  # 30

# Dictionary comprehension
squares = {x: x**2 for x in range(5)}
# {0:0, 1:1, 2:4, 3:9, 4:16}
Strings
String methods
Utilities
text = "  Hello World  "

print(text.strip())      # "Hello World"
print(text.upper())      # "  HELLO WORLD  "
print(text.replace("World", "Python"))

# Formatting
name = "Alice"
print(f"Hello {name}!")  # Hello Alice!
Classes
Object-oriented programming
OOP
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"Hello, I'm {self.name}"

class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade
Error Handling
Exception handling
Error Handling
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"Error: {e}")
finally:
    print("Cleanup")
File I/O
Reading and writing files
File I/O
# Write file
with open('file.txt', 'w') as f:
    f.write("Hello World!")

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

# Read lines
with open('file.txt', 'r') as f:
    for line in f:
        print(line.strip())
Modules
Importing modules
Modules
# Import modules
import math
import random
from datetime import datetime

# Import specific
from math import pi, sqrt
from random import choice, randint

# Create module
# utils.py
def add(a, b):
    return a + b

# main.py  
from utils import add
Decorators
Function decorators
Advanced
def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before function")
        result = func(*args, **kwargs)
        print("After function")
        return result
    return wrapper

@my_decorator
def greet(name):
    print(f"Hello {name}!")

greet("Alice")
Generators
Generator functions
Advanced
# Generator function
def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

# Usage
for num in count_up_to(5):
    print(num)

# Generator expression
squares = (x**2 for x in range(5))
Context Managers
With statements
Advanced
# Built-in
with open('file.txt', 'r') as f:
    content = f.read()

# Custom context manager
class Timer:
    def __enter__(self):
        self.start = time.time()
        return self
    
    def __exit__(self, *args):
        print(f"Time: {time.time() - self.start:.2f}s")

with Timer():
    time.sleep(1)
Lambda & Map/Filter
Functional programming
Advanced
# Lambda functions
square = lambda x: x ** 2
add = lambda x, y: x + y

# Map
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
# [1, 4, 9, 16]

# Filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4]
Collections
Specialized data types
Data Structures
from collections import Counter, defaultdict, deque

# Counter
text = "hello world"
count = Counter(text)
print(count.most_common(3))

# Defaultdict
dd = defaultdict(list)
dd['fruits'].append('apple')

# Deque
dq = deque([1, 2, 3])
dq.appendleft(0)
dq.append(4)
JSON
JSON operations
Utilities
import json

# Python to JSON
data = {"name": "Alice", "age": 30}
json_str = json.dumps(data)

# JSON to Python
parsed = json.loads(json_str)

# File operations
with open('data.json', 'w') as f:
    json.dump(data, f)

with open('data.json', 'r') as f:
    loaded = json.load(f)
Datetime
Date and time operations
Utilities
from datetime import datetime, timedelta

# Current time
now = datetime.now()

# Specific date
dt = datetime(2024, 1, 15, 14, 30)

# Formatting
formatted = now.strftime("%Y-%m-%d %H:%M")

# Time arithmetic
tomorrow = now + timedelta(days=1)
Regular Expressions
Pattern matching
Utilities
import re

text = "Contact: support@example.com"

# Find email
email_pattern = r'\b[\w.-]+@[\w.-]+\.\w+\b'
emails = re.findall(email_pattern, text)

# Search
match = re.search(email_pattern, text)
if match:
    print(match.group())

# Replace
new_text = re.sub(r'\d', 'X', "123-456-7890")
HTTP Requests
Web requests
Web
import requests

# GET request
response = requests.get('https://api.example.com/data')
data = response.json()

# POST request
payload = {"name": "Alice", "age": 30}
response = requests.post('https://api.example.com/users', json=payload)
Virtual Environments
Environment management
Tools
# Create virtual environment
# python -m venv myenv

# Activate (Windows)
# myenv\Scripts\activate

# Activate (Unix/MacOS)
# source myenv/bin/activate

# Install packages
# pip install requests pandas numpy

# Requirements file
# pip freeze > requirements.txt
Type Hints
Type annotations
Advanced
# Basic type hints
def greet(name: str) -> str:
    return f"Hello {name}"

def add(a: int, b: int) -> int:
    return a + b

# Optional types
from typing import Optional, List

def find_user(user_id: int) -> Optional[dict]:
    users = {1: "Alice", 2: "Bob"}
    return users.get(user_id)

def process_items(items: List[str]) -> None:
    for item in items:
        print(item)
Data Classes
Simple classes for data
OOP
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int
    city: str = "Unknown"  # Default value

# Usage
person = Person("Alice", 30)
print(person.name)  # Alice
print(person)       # Person(name='Alice', age=30, city='Unknown')