Python Cheatsheet

Quick reference for Python syntax, data types, control flow, functions, OOP, and common patterns.

Beginner 5 min read 🐍 Python

Python Basics

SyntaxExampleNotes
Variablex = 42No type keyword needed
Printprint(f"x = {x}")f-strings for formatting
Inputname = input("Name: ")Always returns str
Comment# single lineNo multiline comment syntax
Multiline str"""triple quotes"""Also used for docstrings
Type checkisinstance(x, int)Preferred over type()
None checkx is NoneUse is, not ==

Data Types

TypeExampleMutable?
int42, 10**100No
float3.14, 2.998e8No
str"hello", f"{x}"No
boolTrue, FalseNo
list[1, 2, 3]Yes
tuple(1, 2, 3)No
set{1, 2, 3}Yes
dict{"a": 1}Yes
NoneNoneN/A

Strings

s = "Hello, World!"
s.upper()          # "HELLO, WORLD!"
s.lower()          # "hello, world!"
s.strip()          # Remove whitespace
s.split(",")       # ["Hello", " World!"]
"-".join(["a","b"]) # "a-b"
s.replace("World", "Python")
s.startswith("He")  # True
s.find("World")     # 7 (-1 if not found)
f"{name:>10}"       # Right-align
f"{pi:.2f}"         # 2 decimal places

Lists

lst = [1, 2, 3]
lst.append(4)       # Add to end
lst.insert(0, 0)    # Insert at index
lst.extend([5, 6])  # Add multiple
lst.pop()           # Remove last
lst.pop(0)          # Remove at index
lst.remove(3)       # Remove by value
lst.sort()          # In-place sort
lst.reverse()       # In-place reverse
len(lst)            # Length
3 in lst            # Membership test
lst[1:3]            # Slice
lst[::-1]           # Reversed copy
[x**2 for x in lst] # Comprehension

Dictionaries

d = {"a": 1, "b": 2}
d["c"] = 3          # Add/update
d.get("x", 0)       # Safe access with default
d.pop("a")          # Remove and return
d.keys()            # All keys
d.values()          # All values
d.items()           # Key-value pairs
d.setdefault("d", 4)  # Set if missing
d1 | d2             # Merge (3.9+)
{k: v for k, v in d.items()}  # Comprehension

Control Flow

# Conditionals
if x > 0:
    print("positive")
elif x == 0:
    print("zero")
else:
    print("negative")

# Ternary
result = "yes" if condition else "no"

# For loop
for item in iterable:
    pass
for i, val in enumerate(lst):
    pass
for k, v in dict.items():
    pass

# While
while condition:
    pass

# Comprehension
[x for x in range(10) if x % 2 == 0]

Functions

def greet(name, greeting="Hello"):
    """Docstring."""
    return f"{greeting}, {name}!"

# *args, **kwargs
def func(*args, **kwargs):
    pass

# Lambda
square = lambda x: x ** 2
sorted(lst, key=lambda x: x.name)

# Decorators
from functools import wraps
def decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

OOP

class MyClass:
    class_var = "shared"

    def __init__(self, x):
        self.x = x

    def method(self):
        return self.x

    @property
    def value(self):
        return self._value

    @classmethod
    def create(cls, data):
        return cls(data)

    @staticmethod
    def utility():
        pass

    def __repr__(self):
        return f"MyClass({self.x})"

    def __eq__(self, other):
        return self.x == other.x

# Inheritance
class Child(Parent):
    def __init__(self, x, y):
        super().__init__(x)
        self.y = y

# Dataclass
from dataclasses import dataclass
@dataclass
class Point:
    x: float
    y: float

Error Handling

try:
    result = risky_operation()
except ValueError as e:
    print(f"Value error: {e}")
except (TypeError, KeyError):
    print("Type or key error")
except Exception as e:
    print(f"Unexpected: {e}")
else:
    print("No errors!")
finally:
    cleanup()

# Custom exception
class AppError(Exception):
    pass

raise AppError("something failed")

File I/O

# Read
with open("file.txt", "r") as f:
    content = f.read()
    # or: lines = f.readlines()
    # or: for line in f:

# Write
with open("file.txt", "w") as f:
    f.write("hello\n")

# JSON
import json
with open("data.json") as f:
    data = json.load(f)
with open("out.json", "w") as f:
    json.dump(data, f, indent=2)

# pathlib
from pathlib import Path
p = Path("data") / "file.txt"
content = p.read_text()
p.write_text("hello")

Modules & Packages

import math
from datetime import datetime
from collections import Counter, defaultdict
import json

# Virtual environment
# python3 -m venv myenv
# source myenv/bin/activate
# pip install requests
# pip freeze > requirements.txt

# __name__ guard
if __name__ == "__main__":
    main()

Useful Built-ins

FunctionUsageExample
len()Lengthlen([1,2,3]) → 3
range()Number sequencerange(5) → 0,1,2,3,4
enumerate()Index + valuefor i, v in enumerate(lst)
zip()Parallel iterationzip(names, scores)
map()Apply functionmap(str, nums)
filter()Filter elementsfilter(bool, lst)
sorted()New sorted listsorted(lst, key=len)
any()/all()Boolean checkany(x > 0 for x in lst)
isinstance()Type checkisinstance(x, int)
dir()List attributesdir(obj)