โ† Back to all guides

Python TLDR

A rapid reference guide to the Python programming language. Simple, powerful, and readable.

v3.13 โ€” December 2025

What is Python?

Python is a high-level, interpreted programming language emphasizing code readability and simplicity. It supports multiple paradigms: procedural, object-oriented, and functional programming.

Readable Syntax

Clean, English-like syntax with significant whitespace. Code that's easy to write and easier to read.

Dynamic Typing

No type declarations needed. Variables are assigned at runtime with automatic type inference.

Batteries Included

Comprehensive standard library. From web servers to regex to JSON parsing, it's all built in.

Versatile Ecosystem

Massive package ecosystem via pip. Data science, web dev, automation, AI โ€” Python does it all.

Basics

Hello World

print("Hello, world!")

Variables

# Dynamic typing, no declaration needed
x = 42
y = 3.14
name = "Alice"
is_valid = True

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

# Type hints (optional, for static analysis)
age: int = 25
price: float = 19.99
username: str = "bob"

Comments

# Single line comment

"""
Multi-line string literal
Often used as multi-line comments
Also used for docstrings
"""

Operators

# Arithmetic
10 + 3      # 13 (addition)
10 - 3      # 7 (subtraction)
10 * 3      # 30 (multiplication)
10 / 3      # 3.333... (float division)
10 // 3     # 3 (floor division)
10 % 3      # 1 (modulo)
10 ** 3     # 1000 (exponentiation)

# Comparison
x == y      # equal
x != y      # not equal
x < y       # less than
x <= y      # less than or equal

# Logical
and, or, not

# Identity & membership
x is y        # same object
x is not y    # different object
x in collection
x not in collection

Control Flow

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

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

# while loop
while x < 10:
    print(x)
    x += 1

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

for item in collection:
    print(item)

# break, continue, pass
for i in range(10):
    if i == 3:
        continue  # skip to next iteration
    if i == 7:
        break      # exit loop
    pass           # do nothing (placeholder)

match Statement (Python 3.10+)

# Structural pattern matching
match status:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case _:
        print("Unknown")

# Match with patterns
match point:
    case (x, 0):
        print(f"On x-axis at {x}")
    case (0, y):
        print(f"On y-axis at {y}")
    case (x, y):
        print(f"Point at ({x}, {y})")

Data Types

Primitive Types

Type Example Notes
int 42, -17, 0xFF Arbitrary precision integers
float 3.14, 2.0e-8 Double precision (64-bit)
bool True, False Subclass of int
str "hello", 'world' Immutable Unicode strings
NoneType None Null value

Strings

# String literals
s1 = "double quotes"
s2 = 'single quotes'
s3 = """triple quotes
for multi-line strings"""

# String formatting
name = "Alice"
age = 30

# f-strings (preferred, Python 3.6+)
msg = f"{name} is {age} years old"
msg = f"{age + 1}"  # expressions work

# .format() method
msg = "{} is {} years old".format(name, age)

# % formatting (old style)
msg = "%s is %d years old" % (name, age)

# Common string methods
s.upper()           # UPPERCASE
s.lower()           # lowercase
s.strip()           # remove whitespace
s.split(",")         # split into list
",".join(items)    # join list into string
s.replace("a", "b") # replace substring
s.startswith("Hi")
s.endswith(".txt")
s.find("sub")        # index or -1
"sub" in s          # membership test

# String slicing
s[0]      # first character
s[-1]     # last character
s[1:4]   # slice from index 1 to 3
s[:5]    # first 5 characters
s[5:]    # from index 5 to end
s[::-1]  # reverse string

Type Conversion

# Convert between types
int("42")          # str to int
float("3.14")       # str to float
str(42)            # any to str
bool(1)            # any to bool

# Falsy values: False, None, 0, 0.0, "", [], {}, ()
# Everything else is truthy

Collections

Lists (Mutable, Ordered)

# Create list
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# Access & modify
fruits[0]              # "apple" (indexing)
fruits[-1]             # "cherry" (negative indexing)
fruits[1:3]           # ["banana", "cherry"] (slicing)
fruits[0] = "orange"  # modify

# Common methods
fruits.append("grape")     # add to end
fruits.insert(1, "kiwi")  # insert at index
fruits.remove("banana")   # remove first occurrence
item = fruits.pop()      # remove & return last
item = fruits.pop(0)     # remove & return at index
fruits.clear()           # remove all

# List operations
len(fruits)            # length
fruits.count("apple")   # count occurrences
fruits.index("cherry")  # find index
fruits.sort()            # sort in place
fruits.reverse()         # reverse in place
sorted(fruits)         # return new sorted list

# Concatenation & repetition
[1, 2] + [3, 4]       # [1, 2, 3, 4]
[1, 2] * 3            # [1, 2, 1, 2, 1, 2]

Tuples (Immutable, Ordered)

# Create tuple
point = (10, 20)
person = ("Alice", 30, "Engineer")
single = (42,)        # trailing comma for single element

# Unpacking
x, y = point
name, age, job = person

# Tuples are immutable
# point[0] = 15  # TypeError!

# Common operations
len(point)
point.count(10)
point.index(20)

Sets (Mutable, Unordered, Unique)

# Create set
colors = {"red", "green", "blue"}
numbers = set([1, 2, 2, 3])  # {1, 2, 3}
empty = set()             # empty set (not {})

# Add & remove
colors.add("yellow")
colors.remove("red")      # KeyError if not found
colors.discard("purple")  # no error if not found
colors.pop()              # remove arbitrary element

# Set operations
a = {1, 2, 3}
b = {3, 4, 5}

a | b                  # union: {1, 2, 3, 4, 5}
a & b                  # intersection: {3}
a - b                  # difference: {1, 2}
a ^ b                  # symmetric difference: {1, 2, 4, 5}
1 in a                # membership test

Dictionaries (Mutable, Key-Value Pairs)

# Create dictionary
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Access
person["name"]          # "Alice" (KeyError if missing)
person.get("age")      # 30 (returns None if missing)
person.get("job", "Unknown")  # default value

# Modify
person["age"] = 31    # update
person["job"] = "Engineer"  # add new key
del person["city"]    # remove key
person.pop("age")      # remove & return value

# Dictionary methods
person.keys()           # dict_keys(['name', 'job'])
person.values()         # dict_values(['Alice', 'Engineer'])
person.items()          # dict_items([('name', 'Alice'), ...])

# Iteration
for key in person:
    print(key, person[key])

for key, value in person.items():
    print(f"{key}: {value}")

# Merge dictionaries (Python 3.9+)
d1 = {"a": 1}
d2 = {"b": 2}
merged = d1 | d2      # {'a': 1, 'b': 2}

Functions

Defining Functions

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

# Default parameters
def power(base, exponent=2):
    return base ** exponent

# Type hints (optional)
def add(a: int, b: int) -> int:
    return a + b

# Multiple return values (returns tuple)
def min_max(numbers):
    return min(numbers), max(numbers)

minimum, maximum = min_max([1, 2, 3, 4, 5])

Arguments

# *args: variable positional arguments
def sum_all(*args):
    return sum(args)

sum_all(1, 2, 3, 4)  # 10

# **kwargs: variable keyword arguments
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=30)

# Keyword-only arguments (after *)
def divide(a, b, *, precision=2):
    return round(a / b, precision)

divide(10, 3, precision=4)  # must use keyword

Lambda Functions

# Anonymous functions for simple operations
square = lambda x: x ** 2
add = lambda x, y: x + y

# Often used with map, filter, sorted
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))
sorted(students, key=lambda s: s["grade"])

Decorators

# Function wrapper that modifies behavior
def timer(func):
    def wrapper(*args, **kwargs):
        import time
        start = time.time()
        result = func(*args, **kwargs)
        print(f"Took {time.time() - start:.2f}s")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)

# Common built-in decorators
@staticmethod   # method doesn't need self/cls
@classmethod    # method receives class as first arg
@property       # getter for computed attribute

Classes & Objects

Defining Classes

# Basic class
class Person:
    # Constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Instance method
    def greet(self):
        return f"Hi, I'm {self.name}"

    # String representation
    def __str__(self):
        return f"Person({self.name}, {self.age})"

# Create instance
alice = Person("Alice", 30)
print(alice.greet())
print(alice)  # calls __str__

Class & Static Methods

class Circle:
    # Class variable (shared by all instances)
    pi = 3.14159

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

    # Instance method
    def area(self):
        return Circle.pi * self.radius ** 2

    # Class method (receives class as first arg)
    @classmethod
    def from_diameter(cls, diameter):
        return cls(diameter / 2)

    # Static method (no self/cls)
    @staticmethod
    def is_valid_radius(radius):
        return radius > 0

Inheritance

# Parent class
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        pass

# Child class
class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # call parent constructor
        self.breed = breed

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

dog = Dog("Buddy", "Golden Retriever")
print(dog.speak())

Properties & Magic Methods

class Rectangle:
    def __init__(self, width, height):
        self._width = width
        self._height = height

    # Property getter
    @property
    def area(self):
        return self._width * self._height

    # Property setter
    @area.setter
    def area(self, value):
        self._width = value / self._height

    # Operator overloading
    def __add__(self, other):
        return self.area + other.area

r = Rectangle(10, 5)
print(r.area)  # 50 (calls getter)
r.area = 100    # calls setter
Common magic methods: __init__, __str__, __repr__, __len__, __getitem__, __add__, __eq__

Error Handling

Try/Except

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

# Multiple exceptions
try:
    value = int(input("Enter a number: "))
    result = 10 / value
except ValueError:
    print("Invalid number")
except ZeroDivisionError:
    print("Cannot divide by zero")
except Exception as e:
    print(f"Error: {e}")

# else & finally
try:
    file = open("data.txt")
except FileNotFoundError:
    print("File not found")
else:
    # runs if no exception
    content = file.read()
finally:
    # always runs
    if 'file' in locals():
        file.close()

Raising Exceptions

# Raise an exception
def divide(a, b):
    if b == 0:
        raise ValueError("Divisor cannot be zero")
    return a / b

# Custom exceptions
class InvalidAgeError(Exception):
    pass

def set_age(age):
    if age < 0:
        raise InvalidAgeError("Age cannot be negative")
    return age

Common Exceptions

ValueError
Invalid value for operation
TypeError
Wrong type for operation
KeyError
Dictionary key not found
IndexError
List index out of range
FileNotFoundError
File doesn't exist
AttributeError
Attribute doesn't exist

Comprehensions & Generators

List Comprehensions

# Basic list comprehension
squares = [x**2 for x in range(10)]

# With condition
evens = [x for x in range(20) if x % 2 == 0]

# Nested comprehension
matrix = [[i*j for j in range(3)] for i in range(3)]

# String manipulation
words = ["hello", "world", "python"]
upper = [w.upper() for w in words]

# Flatten list
nested = [[1, 2], [3, 4], [5, 6]]
flat = [item for sublist in nested for item in sublist]

Dict & Set Comprehensions

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

# Invert dictionary
original = {"a": 1, "b": 2}
inverted = {v: k for k, v in original.items()}

# Set comprehension
unique = {x % 10 for x in range(100)}

Generator Expressions

# Generator (lazy evaluation, memory efficient)
gen = (x**2 for x in range(1000000))

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

for num in fibonacci(10):
    print(num)

# Infinite generator
def count_up(start=0):
    while True:
        yield start
        start += 1

Files & I/O

Reading Files

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

# Read lines into list
with open("file.txt") as f:
    lines = f.readlines()

# Read line by line (memory efficient)
with open("file.txt") as f:
    for line in f:
        print(line.strip())

Writing Files

# Write (overwrites existing)
with open("output.txt", "w") as f:
    f.write("Hello, world!\n")
    f.writelines(["Line 1\n", "Line 2\n"])

# Append
with open("output.txt", "a") as f:
    f.write("Appended line\n")

File Modes & Working with Paths

# File modes
"r"   # read (default)
"w"   # write (overwrites)
"a"   # append
"r+"  # read and write
"rb"  # read binary
"wb"  # write binary

# Path operations (pathlib, Python 3.4+)
from pathlib import Path

p = Path("data/file.txt")
print(p.exists())       # check if exists
print(p.is_file())      # is it a file?
print(p.name)           # "file.txt"
print(p.suffix)         # ".txt"
print(p.parent)         # "data"

# Read/write with pathlib
text = p.read_text()
p.write_text("New content")

# Iterate directory
for file in Path(".").glob("*.py"):
    print(file)

JSON & CSV

# JSON
import json

data = {"name": "Alice", "age": 30}

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

# Read JSON
with open("data.json") as f:
    data = json.load(f)

# CSV
import csv

# Write CSV
with open("data.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Age"])
    writer.writerow(["Alice", 30])

# Read CSV
with open("data.csv") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

Modules & Packages

Importing Modules

# Import entire module
import math
print(math.pi)

# Import with alias
import numpy as np

# Import specific items
from math import pi, sqrt
print(pi)

# Import all (not recommended)
from math import *

Creating Modules

# mymodule.py
def greet(name):
    return f"Hello, {name}"

class Calculator:
    def add(self, a, b):
        return a + b

# In another file
import mymodule
print(mymodule.greet("Alice"))

Package Structure

mypackage/
โ”œโ”€โ”€ __init__.py      # Makes it a package
โ”œโ”€โ”€ module1.py
โ”œโ”€โ”€ module2.py
โ””โ”€โ”€ subpackage/
    โ”œโ”€โ”€ __init__.py
    โ””โ”€โ”€ module3.py

# Import from package
from mypackage import module1
from mypackage.subpackage import module3

Common Standard Library Modules

import os           # OS interface
import sys          # System parameters
import re           # Regular expressions
import datetime     # Date and time
import random       # Random numbers
import json         # JSON encoding/decoding
import math         # Math functions
import collections  # Specialized containers
import itertools    # Iterator tools
import functools    # Higher-order functions

pip & Virtual Environments

# Install packages
pip install requests
pip install pandas numpy matplotlib

# Create requirements file
pip freeze > requirements.txt

# Install from requirements
pip install -r requirements.txt

# Virtual environment
python -m venv venv
source venv/bin/activate  # Linux/Mac
venv\Scripts\activate     # Windows
deactivate                # Exit virtual environment
Always use virtual environments to isolate project dependencies. Use venv (built-in) or virtualenv for this.