Python Cheat Sheet

A complete quick reference guide for Python syntax, data types, control flow, functions, OOP, modules, and algorithms. Keep this handy.

Welcome to the Poetic Bytes Python Cheat Sheet — your one‑stop, no‑fluff reference for the Python programming language. Whether you're a beginner brushing up on fundamentals or an experienced developer looking for a quick syntax reminder, this page brings together the most essential concepts in a clean, executable format. Every code snippet is accompanied by an explanation that clarifies why the code is written that way, how it runs, what it produces, and where it fits into the bigger picture. You can copy any example with one click or run it live right in your browser (powered by Pyodide). Bookmark this page, share it with your peers, and keep coding with confidence.

🔤 Variables & Data Types

Variable Assignment & Dynamic Typing

Why used: Variables store values for later use. Python is dynamically typed — you don't declare types; the interpreter infers them.
How it operates: Values are assigned with =. Multiple assignments and swapping are supported.
Impact on output: The printed values show the current state of each variable.
Significance: This flexibility speeds up development and reduces boilerplate.

Python variables are dynamically typed. No type declaration needed.

name = "Glenn"
age = 28
height = 1.75
is_student = True
x, y, z = 10, 20, 30
a, b = 5, 10
a, b = b, a
variablesassignmentdynamic

Numeric Types

Why used: Numbers are the foundation of computation. Python supports integers, floating‑point, and complex numbers.
How it operates: Literals are interpreted directly; underscores improve readability. Type conversion functions (int(), float()) are shown.
Impact on output: The printed values demonstrate each numeric representation.
Significance: Understanding numeric types is crucial for math, data analysis, and scientific computing.

Integers, floats, and complex numbers with type conversion.

int_num = 42
float_num = 3.14159
complex_num = 3 + 4j
big_num = 1_000_000
hex_num = 0xFF
oct_num = 0o777
bin_num = 0b1010
intfloatcomplex

String Methods & Operations

Why used: Strings are everywhere — user input, output, data processing. Methods like .strip(), .upper(), and slicing are essential.
How it operates: Each method returns a new string (strings are immutable). Slicing uses [start:stop:step].
Impact on output: The transformed strings are printed, showing the effect of each operation.
Significance: Mastering string manipulation is key for text processing, formatting, and parsing.

Comprehensive string manipulation methods.

s = "  Hello World  "
print(s.strip())
print(s.upper())
print(s.lower())
print(s.capitalize())
print(s.title())
print(s.replace("World", "Python"))
print(s.split())
print("-".join(["a", "b", "c"]))
print(s[0:5])
print(s[6:])
print(s[::-1])
stringsf-stringsslicing

Type Conversion Functions

Why used: Often you need to convert between types (e.g., string to integer for math).
How it operates: Built‑in functions like int(), float(), str() attempt to convert the argument.
Impact on output: The converted values are printed, showing the new type.
Significance: These functions are vital for handling user input and preparing data for processing.

Convert between Python data types.

int("42")
float("3.14")
str(42)
bool(0)
bool("")
bool("hello")
list((1, 2, 3))
tuple([1, 2, 3])
set([1, 2, 2, 3])
dict([("a", 1), ("b", 2)])
intstrlisttuple

Constants & Special Values

Why used: None, True, False are fundamental to Python's logic and control flow.
How it operates: They are singletons; is checks identity. Ellipsis has uses in slicing and type hints.
Impact on output: The boolean operations and identity checks show how these values behave.
Significance: Correct use of these constants is essential for conditionals and function returns.

Python's special constants and built-in values.

None
True
False
NotImplemented
Ellipsis
print(None is None)
print(True and False)
print(Ellipsis)
constantsNoneboolean
⚙️ Operators

Arithmetic Operators

Why used: Perform basic math operations.
How it operates: +, -, *, / (float division), // (floor), % (modulo), ** (power).
Impact on output: The results show the difference between true division and floor division.
Significance: These are the building blocks of any numeric computation.

Basic math operations with examples.

10 + 3
10 - 3
10 * 3
10 / 3
10 // 3
10 % 3
10 ** 3
additiondivisionmodulo

Comparison Operators

Why used: Compare values to make decisions.
How it operates: Return True or False. Works on numbers, strings, and sequences.
Impact on output: The booleans are printed, indicating the truth of each comparison.
Significance: They are the backbone of conditional logic.

Compare values with these operators.

5 == 5
5 != 3
5 < 10
5 > 3
5 <= 5
5 >= 3
comparisonequality

Logical Operators

Why used: Combine boolean conditions.
How it operates: and, or, not return the last evaluated operand (short‑circuit).
Impact on output: The printed results show the truth value of compound conditions.
Significance: Essential for complex conditionals and while loops.

Combine boolean conditions.

True and False
True or False
not True
print(5 > 3 and 10 < 20)
print(5 > 10 or 3 < 5)
logicalandor

Membership & Identity Operators

Why used: Check if an element exists in a container (in) or compare object identity (is).
How it operates: in iterates through the container; is compares memory addresses.
Impact on output: Prints booleans that indicate membership or identity.
Significance: Used for conditional checks and ensuring object equality vs. identity.

Check membership and object identity.

"apple" in ["apple", "banana"]
"grape" not in ["apple", "banana"]
"a" in "hello"
5 in range(10)
x = [1, 2]
y = x
print(x is y)
inismembership

Bitwise Operators

Why used: Work directly with bits — used in low‑level programming, flags, and performance optimisations.
How it operates: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift).
Impact on output: The results show the integer values after bitwise operations.
Significance: Essential for systems programming, networking, and embedded work.

Operate on bits of integers.

5 & 3
5 | 3
5 ^ 3
~5
5 << 1
5 >> 1
bitwiseandorxor
🔄 Control Flow

If-Elif-Else Conditions

Why used: Execute different blocks based on conditions.
How it operates: Checks each condition in order; the first true branch executes. The ternary form value if condition else other provides a compact alternative.
Impact on output: The appropriate message or variable is assigned/printed.
Significance: Fundamental to all decision‑making in code.

Conditional execution with Python's indentation.

if condition:
    statement
elif other_condition:
    statement
else:
    statement

result = "Pass" if score >= 70 else "Fail"
ifelifelseternary

For Loops

Why used: Iterate over sequences (lists, tuples, strings, dicts, ranges).
How it operates: for item in iterable assigns each item in turn. enumerate adds an index; zip pairs multiple iterables.
Impact on output: Each iteration prints or processes the current element.
Significance: The most common loop for working with collections.

Iterate over sequences with for loops.

for item in iterable:
    print(item)

for i, value in enumerate(items, start=1):
    print(i, value)

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

While Loops

Why used: Repeat a block while a condition holds. Useful when the number of iterations is not known upfront.
How it operates: The condition is evaluated before each iteration. break exits early; continue skips to the next iteration.
Impact on output: Prints values only for odd numbers (skipping evens) and stops when the break condition is met.
Significance: Essential for input validation, game loops, and indefinite iteration.

Loop while a condition remains true.

while condition:
    statement

while True:
    if condition:
        break

count = 0
while count < 10:
    count += 1
    if count % 2 == 0:
        continue
    print(count)
whilebreakcontinue

Match Statement (Python 3.10+)

Why used: Structural pattern matching offers a powerful, expressive alternative to long if-elif chains.
How it operates: The match expression is compared against patterns (literal values, variable captures, guards).
Impact on output: Prints a message based on the value and its shape (e.g., a point tuple).
Significance: Enables concise and readable code for complex data structures.

Structural pattern matching with examples.

match value:
    case 0:
        print("Zero")
    case n if n > 0:
        print("Positive")
    case _:
        print("Other")
matchpattern matching
📋 Data Structures

List Methods & Operations

Why used: Lists are ordered, mutable sequences — the workhorse of Python data structures.
How it operates: Methods like append, insert, pop, remove, sort modify the list in place. List comprehensions build new lists concisely.
Impact on output: The mutated list and new lists are printed, showing the transformations.
Significance: Lists are used everywhere; comprehension is a Pythonic way to create transformed lists.

Comprehensive list methods and comprehensions.

numbers = [1, 2, 3]
numbers.append(4)
numbers.insert(0, 0)
value = numbers.pop()
numbers.remove(2)
numbers.sort()
squares = [x**2 for x in range(5)]
evens = [x for x in range(10) if x % 2 == 0]
listscomprehensionsmethods

Dictionary Methods & Operations

Why used: Dictionaries map keys to values, enabling fast lookups and data organisation.
How it operates: Key assignment, get (with default), pop, keys, values, items allow flexible manipulation. Dict comprehensions create new dicts.
Impact on output: The modified dict and extracted values are printed.
Significance: Dictionaries are fundamental for data interchange (e.g., JSON), configuration, and caching.

Key-value store operations and comprehensions.

person = {"name": "Alice", "age": 30}
person["city"] = "New York"
name = person.get("name", "Unknown")
age = person.pop("age")
keys = person.keys()
values = person.values()
items = person.items()
squares = {x: x**2 for x in range(5)}
dictgetcomprehensions

Set Methods & Operations

Why used: Sets store unique elements and support fast membership tests and mathematical operations.
How it operates: add, discard, remove modify the set; union (|), intersection (&), difference (-), symmetric difference (^) perform set algebra.
Impact on output: Prints the results of set operations and comprehensions.
Significance: Ideal for deduplication, membership checks, and relational data.

Set operations and methods for unique collections.

a = {1, 2, 3}
b = {3, 4, 5}
a.add(6)
a.discard(2)
a.remove(3)
print(a | b)
print(a & b)
print(a - b)
print(a ^ b)
squares = {x**2 for x in range(5)}
setsunionintersection

Tuple & Unpacking

Why used: Tuples are immutable, often used for fixed‑size collections and to return multiple values from functions.
How it operates: Packing and unpacking allow clean assignment. namedtuple adds field names for readability.
Impact on output: The unpacked variables and the namedtuple are printed.
Significance: Tuples are memory‑efficient and safe from accidental modification.

Immutable sequences with powerful unpacking.

coords = (3, 4)
x, y = coords
first, *rest = [1, 2, 3, 4]
single = (42,)
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y)
tuplesunpackingnamedtuple

Range & Slice Operations

Why used: range generates arithmetic progressions without storing all values; slicing extracts subsequences.
How it operates: range(start, stop, step); slicing syntax [start:stop:step] works on strings, lists, tuples.
Impact on output: Prints the generated list and the sliced results.
Significance: Range is memory‑efficient for loops; slicing is a compact way to get sub‑sequences.

Generate sequences and slice collections.

range(10)
range(2, 10)
range(2, 10, 2)
list(range(5))
s = [0, 1, 2, 3, 4, 5]
s[1:4]
s[::2]
s[1::2]
s[-1]
s[-3:]
s[:3]
rangeslicingindexing
🛠️ Functions

Function Definition & Arguments

Why used: Functions encapsulate reusable code, improving organisation and maintainability.
How it operates: def defines a function; parameters can be positional, keyword, with default values, variable‑length (*args, **kwargs).
Impact on output: The function returns and/or prints the result.
Significance: Functions are the fundamental building blocks of Python programs.

Define functions with various argument types.

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

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

def print_kwargs(**kwargs):
    for key, value in kwargs.items():
        print(key, value)
def*args**kwargs

Lambda Functions

Why used: Small, anonymous functions are perfect for short‑lived operations like sorting keys or map/filter.
How it operates: lambda arguments: expression. They are limited to a single expression.
Impact on output: The results of applying lambdas through map, filter, and sorted are printed.
Significance: Lambdas enable functional‑style programming and reduce boilerplate.

Anonymous functions for quick operations.

square = lambda x: x**2
add = lambda a, b: a + b
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))
lambdamapfilter

Decorators

Why used: Decorators modify or enhance functions without changing their source code — used for logging, timing, access control.
How it operates: A decorator is a function that takes a function and returns a new function. @wraps preserves metadata.
Impact on output: The decorated function prints execution time before returning the result.
Significance: Decorators promote separation of concerns and code reuse.

Modify or extend function behaviour.

import time
from functools import wraps

def timer(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"Time: {end - start:.4f}s")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)
    return "Done"
decorator@wraps

Closures

Why used: Closures allow a function to “remember” the environment in which it was created — useful for factory functions and stateful functions.
How it operates: The inner function captures variables from the outer scope; nonlocal allows modification.
Impact on output: The returned function retains the captured factor or counter state.
Significance: Enables functional programming patterns and callback creation.

Functions that remember their enclosing scope.

def make_multiplier(factor):
    def multiplier(x):
        return x * factor
    return multiplier

double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5))
print(triple(5))

def counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment
closurenonlocalfactory
🏗️ Object-Oriented Programming

Class Definition & Methods

Why used: Classes model real‑world entities and encapsulate data and behaviour.
How it operates: __init__ initialises attributes; methods have self as first parameter to access instance data.
Impact on output: The car object’s state (odometer) updates with each drive, and the string representation is customised.
Significance: OOP is the paradigm for building scalable, maintainable systems.

Define classes with attributes and methods.

class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model
        self.odometer = 0

    def drive(self, miles):
        self.odometer += miles
        return f"Driven {miles} miles"

    def __str__(self):
        return f"{self.make} {self.model}"
class__init__self

Inheritance & super()

Why used: Inheritance allows a class to reuse and extend the behaviour of another class.
How it operates: The child class overrides methods and can call parent methods with super().
Impact on output: Each animal produces its own sound, and the GoldenRetriever adds extra info.
Significance: Promotes code reuse and establishes hierarchical relationships.

Extend and override classes.

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"
inheritancesuperoverride

Property Decorators

Why used: Properties allow controlled access to attributes, enabling validation and computed values.
How it operates: @property defines a getter; @name.setter defines a setter that validates input.
Impact on output: The name is retrieved and modified; an error is raised when an empty value is attempted.
Significance: Encapsulation without losing the simplicity of attribute access.

Getters, setters, and deleters.

class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        if not value:
            raise ValueError("Name cannot be empty")
        self._name = value
@propertygettersetter

Dataclasses

Why used: Dataclasses automatically generate __init__, __repr__, and more, reducing boilerplate.
How it operates: The @dataclass decorator adds special methods; field allows default factory. Frozen dataclasses are immutable.
Impact on output: The auto‑generated repr shows all fields; properties like is_adult are computed.
Significance: Dataclasses are the modern, clean way to define data‑carrying classes.

Reduce boilerplate with dataclasses.

from dataclasses import dataclass, field

@dataclass
class Person:
    name: str
    age: int
    email: str = ""
    hobbies: list = field(default_factory=list)

    @property
    def is_adult(self) -> bool:
        return self.age >= 18
dataclassfieldfrozen

Class & Static Methods

Why used: Class methods operate on the class itself (factory methods); static methods are utility functions grouped in the class.
How it operates: @classmethod receives the class as first argument; @staticmethod receives no special first argument.
Impact on output: The class method creates an instance; static methods compute results without instance state.
Significance: They provide alternative constructors and organise related functions.

Methods that work with the class itself.

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

    @classmethod
    def from_string(cls, s):
        parts = s.split(",")
        return cls(int(parts[0]), int(parts[1]))
staticmethodclassmethod
⚡ Advanced Python

Generators & Yield

Why used: Generators produce values lazily, saving memory and enabling infinite sequences.
How it operates: yield returns a value and pauses the function; the state is preserved for the next call.
Impact on output: The Fibonacci numbers are generated on‑the‑fly and printed one by one.
Significance: Ideal for processing large files or streams without loading everything into memory.

Lazy iteration with generators.

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

def read_large_file(path):
    with open(path, encoding="utf-8") as f:
        for line in f:
            yield line.strip()
generatoryieldlazy

Context Managers

Why used: Context managers ensure resources (files, connections) are properly acquired and released.
How it operates: The with statement calls __enter__ and __exit__; the contextlib decorator simplifies creation.
Impact on output: The file is opened, written, and automatically closed, as shown by the print statements.
Significance: Prevents resource leaks and makes code robust.

Resource management with the with statement.

class ManagedFile:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

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

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

Async/Await

Why used: Async/await enables concurrent I/O‑bound tasks, improving performance and responsiveness.
How it operates: async def defines a coroutine; await yields control to the event loop; asyncio.gather runs multiple tasks concurrently.
Impact on output: The data from multiple APIs is fetched concurrently, reducing total wait time.
Significance: Crucial for web scraping, real‑time applications, and high‑performance servers.

Asynchronous programming for I/O-bound tasks.

import asyncio

async def fetch_data(name, delay):
    await asyncio.sleep(delay)
    return f"Data from {name}"

async def main():
    results = await asyncio.gather(
        fetch_data("API 1", 1),
        fetch_data("API 2", 0.5),
        fetch_data("API 3", 1.5)
    )
    for result in results:
        print(result)
asyncawaitasyncio

Type Hints & Generics

Why used: Type hints improve code clarity, enable static type checking (mypy), and assist IDEs.
How it operates: Annotations specify expected types; generics (TypeVar) allow parameterised types.
Impact on output: The functions still run as normal, but the types are now documented.
Significance: Helps catch bugs early and facilitates collaboration on larger projects.

Add type information for better tooling.

from typing import List, Dict, Optional, TypeVar, Generic

T = TypeVar("T")

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

def find_user(id: int) -> Optional[Dict[str, str]]:
    return {"name": "Alice"}

def process(items: List[int]) -> List[int]:
    return [i * 2 for i in items]
type hintsgenericstyping

Descriptors

Why used: Descriptors control attribute access at the class level, enabling reusable property logic.
How it operates: __set_name__, __get__, __set__ manage the attribute. This example enforces positive values.
Impact on output: The price and quantity are set; an error is raised when a negative value is assigned.
Significance: Provides a powerful mechanism for data validation, ORMs, and framework internals.

Control attribute access in classes.

class PositiveNumber:
    def __set_name__(self, owner, name):
        self.name = name

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return obj.__dict__.get(self.name, 0)

    def __set__(self, obj, value):
        if value < 0:
            raise ValueError("Must be positive")
        obj.__dict__[self.name] = value
descriptor__get____set__
📁 File I/O & Error Handling

File Operations

Why used: Read from and write to files for data persistence and configuration.
How it operates: open() with modes 'r', 'w', 'a'; using with ensures the file is closed automatically.
Impact on output: The file is created/overwritten/appended, and its content is printed.
Significance: Fundamental for any application that needs to store or read data.

Read, write, and append files.

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

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

with open("file.txt", "a") as f:
    f.write("New line")
file I/Oreadwrite

JSON Handling

Why used: JSON is the most common data interchange format for web APIs and configuration files.
How it operates: json.dumps serialises Python objects to JSON strings; json.loads parses JSON back to Python.
Impact on output: The formatted JSON string is printed, then the parsed data is accessed.
Significance: Enables seamless data exchange between Python and other systems.

Encode and decode JSON data.

import json

data = {"name": "Alice", "age": 30}
json_str = json.dumps(data, indent=2)
parsed = json.loads(json_str)
jsondumpsloads

Exception Handling

Why used: Handle errors gracefully to prevent crashes and provide useful feedback.
How it operates: try block contains risky code; except catches specific exceptions; else runs if no exception; finally always runs.
Impact on output: The division result or error message is printed; cleanup is performed.
Significance: Makes applications robust and user‑friendly.

Graceful error handling with try/except.

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
except ValueError:
    print("Invalid value")
else:
    print("Success")
finally:
    print("Cleanup")
try/exceptfinallyexceptions

Custom Exceptions

Why used: Create domain‑specific exceptions to convey clear error information.
How it operates: Inherit from Exception (or a subclass), add attributes like code or field.
Impact on output: The custom exception is raised and caught, printing the error code and message.
Significance: Improves error handling by providing context that is specific to your application.

Create your own exception classes.

class CustomError(Exception):
    def __init__(self, message, code):
        super().__init__(message)
        self.code = code
custom exceptionraise
🧰 Built-in Functions Reference
print() – Output to console
len() – Length of sequence
type() – Type of object
int() – Convert to int
float() – Convert to float
str() – Convert to string
list() – Convert to list
dict() – Create dict
set() – Create set
tuple() – Convert to tuple
sum() – Sum iterable
max() – Maximum value
min() – Minimum value
sorted() – Sorted list
enumerate() – Index-value pairs
zip() – Zip iterables
any() – Check if any truthy
all() – Check if all truthy
filter() – Filter iterable
map() – Map function
range() – Generate range
input() – Read input
isinstance() – Type check
abs() – Absolute value
round() – Round number
open() – Open file
help() – Get help
dir() – List attributes
id() – Object identity
hash() – Hash value
bool() – Convert to boolean
iter() – Get iterator
next() – Next item
reversed() – Reverse iterable
chr() – Unicode character
ord() – Unicode code point
📚 Standard Library Modules

Essential Modules

  • math – Mathematical functions
  • random – Random number generation
  • datetime – Date and time
  • json – JSON encoding/decoding
  • csv – CSV file handling
  • re – Regular expressions
  • itertools – Iterator tools
  • collections – Specialized containers
  • functools – Higher-order functions
  • os – Operating system interface
  • sys – System-specific parameters
  • pathlib – Object-oriented path handling
  • argparse – Command-line parsing
  • logging – Logging framework
  • hashlib – Cryptographic hashing
  • subprocess – Run external commands

collections & itertools

  • Counter – Count hashable objects
  • defaultdict – Missing keys default
  • deque – Double-ended queue
  • OrderedDict – Maintains insertion order
  • namedtuple – Tuples with named fields
  • chain() – Chain iterables
  • groupby() – Group consecutive items
  • combinations() – All combinations
  • permutations() – All permutations
  • product() – Cartesian product
  • islice() – Slice iterator
  • count() – Infinite counter
  • cycle() – Infinite cycle
  • repeat() – Repeat value
🧮 Algorithms Quick Reference

Binary Search

Why used: Efficiently find an element in a sorted array in O(log n) time.
How it operates: Repeatedly divides the search interval in half, comparing the target with the middle element.
Impact on output: Returns the index of the target or -1 if not found, printed for each search.
Significance: Classic algorithm used in many libraries and problem‑solving.

Efficient search in sorted arrays.

def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1
binary searchO(log n)

Quicksort

Why used: Quicksort is one of the fastest sorting algorithms (average O(n log n)).
How it operates: Pick a pivot, partition the array into elements less than, equal to, and greater than the pivot, then recursively sort the sub‑arrays.
Impact on output: The unsorted list is transformed into a sorted list, printed side‑by‑side.
Significance: Widely used in practice; demonstrates the divide‑and‑conquer approach.

Efficient divide-and-conquer sorting algorithm.

def quicksort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quicksort(left) + middle + quicksort(right)
quicksortO(n log n)

Factorial & Recursion

Why used: Recursion is a powerful technique where a function calls itself; factorial and Fibonacci are classic examples.
How it operates: The base case stops recursion; lru_cache memoizes results to avoid repeated calculations.
Impact on output: The factorial and Fibonacci numbers are computed and printed for a range of inputs.
Significance: Recursion simplifies problems that can be broken into smaller, identical sub‑problems.

Classic recursive examples with memoization.

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)
recursionfactorialmemoization
🧪 Testing Quick Reference

pytest Basics

Why used: Testing ensures code works as expected; pytest makes tests concise and readable.
How it operates: Write functions prefixed with test_ and use assert to verify outcomes.
Impact on output: When run, pytest reports whether tests pass or fail; here we simulate a successful run.
Significance: Automated testing is essential for maintaining code quality.

Write and run tests with pytest.

def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
pytestasserttesting

unittest Basics

Why used: Unittest is Python's built‑in testing framework, compatible with many CI systems.
How it operates: Define a subclass of TestCase and write methods starting with test_; use assertion methods like assertEqual.
Impact on output: The test runner executes all tests and reports success or failure.
Significance: Provides a solid foundation for writing unit tests without external dependencies.

Python's built-in testing framework.

import unittest

class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(2 + 3, 5)

    def test_positive(self):
        self.assertTrue(5 > 0)
unittesttestingassert
Bookmark this cheat sheet for quick reference while coding.

🎯 Final words — This cheat sheet is designed to be your go‑to reference for Python programming. Each snippet has been carefully chosen to illustrate a core concept, with explanations that connect the why and how behind the code. Use it to refresh your memory, learn new patterns, or share it with your fellow developers. Remember, coding is not just about writing syntax — it's about solving problems with clarity and efficiency. Keep this page close, and happy coding!