Python
Cheat Sheet

Essential syntax, data structures, OOP, and common patterns. From basics to advanced.

Variables & Data Types

Basic Types

x = 42          # int
y = 3.14        # float
s = "hello"     # str
b = True        # bool
n = None        # NoneType

Containers

lst = [1, 2, 3]        # list
tup = (1, 2, 3)        # tuple
s = {1, 2, 3}          # set
d = {"a": 1, "b": 2}   # dict

Control Flow

Conditionals

if x > 0:
    positive
elif x == 0:
    zero
else:
    negative

Loops

for i in range(10):
    print(i)

while x > 0:
    x -= 1

Functions

Basic Function

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

Lambda

square = lambda x: x ** 2
add = lambda a, b: a + b

List Comprehensions

Basic

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

Dictionary

squares_dict = {x: x**2 for x in range(10)}

OOP

Class Definition

class Dog:
    def __init__(self, name):
        self.name = name
    
    def bark(self):
        return f"{self.name} says woof!"

Inheritance

class Puppy(Dog):
    def bark(self):
        return f"{self.name} says yap!"

Download

Print this page or save as PDF for quick reference.

Tip: Use Ctrl+P (Cmd+P on Mac) to print or save as PDF.