AI Generate Python docs instantly

Python Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

Getting Started

5 snippets

Your first steps with Python basics

Hello World

print("Hello, World!")

Comments

# Single line comment
"""Multi-line
comment"""

User Input

name = input("Enter your name: ")

Type Conversion

int("42")  # str to int
str(42)    # int to str
float("3.14")

Check Type

type(variable)  # <class 'int'>
isinstance(x, int)  # True/False

Variables & Data Types

10 snippets

Declaring and using different data types

String

name = "John"

Integer

age = 25

Float

price = 19.99

Boolean

is_active = True

List

fruits = ["apple", "banana", "cherry"]

Dictionary

person = {"name": "John", "age": 30}

Tuple

coordinates = (10, 20)

Set

unique = {1, 2, 3}

None

value = None

Multiple Assignment

a, b, c = 1, 2, 3
x = y = z = 0

Operators

7 snippets

Symbols for calculations and comparisons

Arithmetic

5 + 3   # 8 (addition)
5 - 3   # 2 (subtraction)
5 * 3   # 15 (multiplication)
5 / 3   # 1.666... (division)
5 // 3  # 1 (floor division)
5 % 3   # 2 (modulus)
5 ** 3  # 125 (exponent)

Comparison

5 == 5  # True (equal)
5 != 3  # True (not equal)
5 > 3   # True (greater)
5 < 3   # False (less)
5 >= 5  # True (greater or equal)
5 <= 3  # False (less or equal)

Logical

True and False  # False
True or False   # True
not True        # False

# Short-circuit evaluation
x and y  # y if x is truthy
x or y   # x if x is truthy

Assignment

x = 5    # Assign
x += 3   # x = 8 (add)
x -= 2   # x = 6 (subtract)
x *= 2   # x = 12 (multiply)
x /= 3   # x = 4.0 (divide)
x //= 2  # x = 2.0 (floor)

Identity

a = [1, 2]
b = a
c = [1, 2]

a is b      # True (same object)
a is c      # False (different object)
a is not c  # True

Membership

"a" in "abc"       # True
2 in [1, 2, 3]     # True
"x" not in "abc"   # True
"key" in {"key": 1}  # True

Bitwise

5 & 3   # 1 (AND: 101 & 011)
5 | 3   # 7 (OR: 101 | 011)
5 ^ 3   # 6 (XOR: 101 ^ 011)
~5      # -6 (NOT)
5 << 1  # 10 (left shift)
5 >> 1  # 2 (right shift)

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Loops

10 snippets

Repeating code blocks efficiently

For Range

for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

For Range Start/End

for i in range(2, 8):
    print(i)  # 2, 3, 4, 5, 6, 7

For Range Step

for i in range(0, 10, 2):
    print(i)  # 0, 2, 4, 6, 8

For List

for fruit in fruits:
    print(fruit)

For Enumerate

for i, fruit in enumerate(fruits):
    print(i, fruit)

For Dict

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

While

while count < 10:
    count += 1

Break

for i in range(10):
    if i == 5:
        break  # Exit loop

Continue

for i in range(10):
    if i == 5:
        continue  # Skip iteration

Else in Loop

for i in range(5):
    print(i)
else:
    print("Done!")  # Runs if no break

Conditionals

5 snippets

Making decisions in your code

If/Else

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

Ternary

result = "yes" if condition else "no"

Match (3.10+)

match status:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case _:
        print("Unknown")

Nested If

if x > 0:
    if x > 10:
        print("big positive")
    else:
        print("small positive")

Multiple Conditions

if age >= 18 and age <= 65:
    print("Working age")

Comprehensions

6 snippets

Concise syntax for creating collections

List Comprehension

squares = [x**2 for x in range(10)]

With Condition

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

Dict Comprehension

squares = {x: x**2 for x in range(5)}

Set Comprehension

unique = {x % 3 for x in range(10)}

Generator Expression

gen = (x**2 for x in range(10))

Nested Comprehension

matrix = [[j for j in range(3)] for i in range(3)]

Functions

5 snippets

Basic Function

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

Default Args

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

Lambda

square = lambda x: x ** 2

*args

def sum_all(*args):
    return sum(args)

**kwargs

def print_info(**kwargs):
    for k, v in kwargs.items():
        print(f"{k}: {v}")

String Operations

6 snippets

F-string

f"Hello, {name}!"

Split

"a,b,c".split(",")  # ["a", "b", "c"]

Join

",".join(["a", "b", "c"])  # "a,b,c"

Strip

"  hello  ".strip()  # "hello"

Replace

"hello".replace("l", "x")  # "hexxo"

Slice

"hello"[1:4]  # "ell"

File I/O

3 snippets

Read File

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

Write File

with open("file.txt", "w") as f:
    f.write("Hello")

Read Lines

with open("file.txt") as f:
    lines = f.readlines()

Error Handling

3 snippets

Try/Except

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

Finally

try:
    risky_operation()
except Exception as e:
    print(e)
finally:
    cleanup()

Raise

raise ValueError("Invalid input")

Classes & OOP

2 snippets

Class

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        return f"{self.name} says woof!"

Inheritance

class Puppy(Dog):
    def play(self):
        return f"{self.name} is playing!"

Imports & Modules

3 snippets

Import

import os

From Import

from datetime import datetime

Alias

import numpy as np

Decorators

6 snippets

Modify function behavior elegantly

Basic Decorator

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before")
        result = func(*args, **kwargs)
        print("After")
        return result
    return wrapper

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

Decorator with Args

def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat(3)
def greet():
    print("Hi!")

@property

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        self._radius = max(0, value)

@staticmethod

class Math:
    @staticmethod
    def add(a, b):
        return a + b

Math.add(2, 3)  # No instance needed

@classmethod

class Person:
    count = 0

    @classmethod
    def get_count(cls):
        return cls.count

functools.wraps

from functools import wraps

def decorator(func):
    @wraps(func)  # Preserves metadata
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

Dataclasses

5 snippets

Simplified class definitions for data

Basic Dataclass

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

p = Point(1.0, 2.0)

Default Values

@dataclass
class User:
    name: str
    age: int = 0
    active: bool = True

Frozen (Immutable)

@dataclass(frozen=True)
class Config:
    host: str
    port: int

Field Options

from dataclasses import dataclass, field

@dataclass
class Item:
    name: str
    tags: list = field(default_factory=list)
    _id: int = field(repr=False)

Post Init

@dataclass
class Rectangle:
    width: float
    height: float
    area: float = field(init=False)

    def __post_init__(self):
        self.area = self.width * self.height

Type Hints

7 snippets

Add type annotations for better code

Basic Types

name: str = "John"
age: int = 30
price: float = 19.99
is_active: bool = True

Collections

from typing import List, Dict, Set, Tuple

nums: List[int] = [1, 2, 3]
scores: Dict[str, int] = {"a": 1}
unique: Set[str] = {"x", "y"}
point: Tuple[int, int] = (1, 2)

Optional

from typing import Optional

def find(id: int) -> Optional[str]:
    return None  # or return "found"

Union

from typing import Union

def process(val: Union[int, str]) -> str:
    return str(val)

Callable

from typing import Callable

def apply(func: Callable[[int], int], x: int) -> int:
    return func(x)

TypeVar (Generics)

from typing import TypeVar, List

T = TypeVar('T')

def first(items: List[T]) -> T:
    return items[0]

Python 3.10+

# Simpler syntax in 3.10+
def greet(name: str | None = None) -> str:
    return f"Hello, {name or 'World'}"

list[int]  # Instead of List[int]

Context Managers

4 snippets

Resource management with 'with' statement

Class-based

class FileManager:
    def __init__(self, filename):
        self.filename = filename

    def __enter__(self):
        self.file = open(self.filename)
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()

@contextmanager

from contextlib import contextmanager

@contextmanager
def timer():
    import time
    start = time.time()
    yield
    print(f"Elapsed: {time.time() - start:.2f}s")

Multiple Contexts

with open("in.txt") as f_in, open("out.txt", "w") as f_out:
    f_out.write(f_in.read())

Suppress Errors

from contextlib import suppress

with suppress(FileNotFoundError):
    os.remove("temp.txt")

Walrus Operator (3.8+)

4 snippets

Assignment expressions with :=

Basic Usage

# Assign and use in one expression
if (n := len(items)) > 10:
    print(f"Too many: {n}")

While Loop

while (line := file.readline()):
    process(line)

List Comprehension

# Avoid calling function twice
results = [y for x in data if (y := process(x)) is not None]

Regex Match

import re
if (match := re.search(r'\d+', text)):
    print(match.group())

Common Standard Library

6 snippets

Frequently used built-in modules

json

import json

# Parse JSON
data = json.loads('{"name": "John"}')

# To JSON string
json_str = json.dumps(data, indent=2)

# File operations
with open("data.json") as f:
    data = json.load(f)

re (Regex)

import re

re.search(r'\d+', text)      # First match
re.findall(r'\d+', text)     # All matches
re.sub(r'\d+', 'X', text)    # Replace
re.split(r'[,;]', text)      # Split

collections

from collections import defaultdict, Counter, deque

# Auto-initialize missing keys
d = defaultdict(list)
d['key'].append(1)

# Count occurrences
counts = Counter(['a', 'b', 'a'])
counts.most_common(2)

# Double-ended queue
dq = deque([1, 2, 3])
dq.appendleft(0)

itertools

from itertools import chain, groupby, islice

# Flatten lists
list(chain([1,2], [3,4]))  # [1,2,3,4]

# Take first n items
list(islice(range(100), 5))  # [0,1,2,3,4]

pathlib

from pathlib import Path

p = Path("folder/file.txt")
p.exists()       # Check existence
p.read_text()    # Read file
p.parent         # Parent directory
p.suffix         # ".txt"
list(p.parent.glob("*.py"))  # Find files

datetime

from datetime import datetime, timedelta

now = datetime.now()
today = datetime.today().date()

# Parse string
dt = datetime.strptime("2024-01-15", "%Y-%m-%d")

# Format
dt.strftime("%B %d, %Y")  # "January 15, 2024"

# Math
tomorrow = now + timedelta(days=1)

More Cheat Sheets

FAQ

Frequently asked questions

What is a Python cheat sheet?

A Python cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in Python. It helps developers quickly look up syntax without searching through documentation.

How do I learn Python quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important Python concepts?

Key Python concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my Python code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your Python code using AI.

Code Conversion Tools

Convert Python to Other Languages

Easily translate your Python code to other programming languages with our AI-powered converters

Related resources

Stop memorizing. Start shipping.

Generate Python Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week