Python Cheat Sheet

Beginner | 15 min read | 2025.01.10

Basic Syntax

Variables and Types

# Variables
name = "Alice"
age = 25
price = 19.99
is_active = True

# Type checking
type(name)  # <class 'str'>

# Type conversion
int("42")      # 42
str(42)        # "42"
float("3.14")  # 3.14
bool(1)        # True
list("abc")    # ['a', 'b', 'c']

Strings

# Formatting
name = "Alice"
f"Hello, {name}!"  # f-string (recommended)
"Hello, {}!".format(name)
"Hello, %s!" % name

# Methods
s = "hello world"
s.upper()        # "HELLO WORLD"
s.lower()        # "hello world"
s.capitalize()   # "Hello world"
s.title()        # "Hello World"
s.strip()        # Remove whitespace
s.split()        # ['hello', 'world']
s.replace("l", "L")  # "heLLo worLd"
s.startswith("h")    # True
s.endswith("d")      # True
"o" in s         # True

# Slicing
s[0]      # 'h'
s[-1]     # 'd'
s[0:5]    # 'hello'
s[::2]    # 'hlowrd'
s[::-1]   # 'dlrow olleh' (reversed)

Lists

# Creation
items = [1, 2, 3, 4, 5]
items = list(range(1, 6))

# Operations
items.append(6)        # Append to end
items.insert(0, 0)     # Insert at position
items.extend([7, 8])   # Concatenate
items.pop()            # Remove and return last item
items.pop(0)           # Remove and return at position
items.remove(3)        # Remove by value
items.index(2)         # Index of value
items.count(2)         # Count occurrences
items.sort()           # Sort (in-place)
items.reverse()        # Reverse (in-place)
sorted(items)          # Sort (returns new list)
len(items)             # Length

# Slicing
items[1:3]     # [2, 3]
items[::2]     # [1, 3, 5]
items[-3:]     # Last 3 items

# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in range(10) if x % 2 == 0]
matrix = [[i*j for j in range(3)] for i in range(3)]

Dictionaries

# Creation
user = {"name": "Alice", "age": 25}
user = dict(name="Alice", age=25)

# Operations
user["email"] = "alice@example.com"  # Add/Update
user.get("name")          # "Alice"
user.get("phone", "N/A")  # Default value
user.keys()               # dict_keys(['name', 'age', 'email'])
user.values()             # dict_values(['Alice', 25, ...])
user.items()              # dict_items([('name', 'Alice'), ...])
user.pop("age")           # Remove and return
user.update({"city": "Tokyo"})  # Merge
"name" in user            # True

# Dictionary comprehension
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Sets

# Creation
s = {1, 2, 3}
s = set([1, 2, 2, 3])  # {1, 2, 3}

# Operations
s.add(4)
s.remove(1)       # Raises error if not found
s.discard(1)      # No error if not found
s.pop()           # Remove a random element

# Set operations
a = {1, 2, 3}
b = {2, 3, 4}
a | b   # Union {1, 2, 3, 4}
a & b   # Intersection {2, 3}
a - b   # Difference {1}
a ^ b   # Symmetric difference {1, 4}

Control Flow

Conditionals

if x > 0:
    print("positive")
elif x < 0:
    print("negative")
else:
    print("zero")

# Ternary operator
result = "even" if x % 2 == 0 else "odd"

# match statement (Python 3.10+)
match status:
    case "pending":
        print("Pending")
    case "approved":
        print("Approved")
    case _:
        print("Unknown")

Loops

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

for item in items:
    print(item)

for i, item in enumerate(items):
    print(i, item)

for key, value in user.items():
    print(key, value)

# while
while condition:
    # Processing
    if should_break:
        break
    if should_skip:
        continue

Functions

# Basic
def greet(name: str) -> str:
    return f"Hello, {name}!"

# Default arguments
def greet(name: str = "World") -> str:
    return f"Hello, {name}!"

# Variable-length arguments
def sum_all(*args):
    return sum(args)

def create_user(**kwargs):
    return kwargs

# Lambda
square = lambda x: x ** 2
sorted(items, key=lambda x: x["name"])

Classes

from dataclasses import dataclass
from typing import Optional

# Standard class
class User:
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

    def greet(self) -> str:
        return f"Hello, {self.name}!"

# dataclass (recommended)
@dataclass
class User:
    name: str
    age: int
    email: Optional[str] = None

    def greet(self) -> str:
        return f"Hello, {self.name}!"

File Operations

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

# Writing
with open("file.txt", "w", encoding="utf-8") as f:
    f.write("Hello, World!")

# JSON
import json

with open("data.json", "r") as f:
    data = json.load(f)

with open("data.json", "w") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

Exception Handling

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Division by zero error")
except Exception as e:
    print(f"Error: {e}")
else:
    print("Success")
finally:
    print("Always executed")

# Raising exceptions
raise ValueError("Invalid value")

Commonly Used Modules

# Path operations
from pathlib import Path
path = Path("dir/file.txt")
path.exists()
path.is_file()
path.read_text()
path.write_text("content")
path.parent
path.stem  # Filename without extension

# Date and time
from datetime import datetime, timedelta
now = datetime.now()
now.strftime("%Y-%m-%d %H:%M:%S")
datetime.strptime("2025-01-10", "%Y-%m-%d")
now + timedelta(days=7)

# Regular expressions
import re
re.match(r"\d+", "123abc")
re.search(r"\d+", "abc123")
re.findall(r"\d+", "a1b2c3")  # ['1', '2', '3']
re.sub(r"\d+", "X", "a1b2")   # "aXbX"

# HTTP
import requests
res = requests.get("https://api.example.com/data")
res.json()
requests.post(url, json={"key": "value"})
← Back to list