Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

4 matches
Errors & debugging easy

How to Raise a Custom Exception with Extra Context in Python

Define a custom exception that carries extra context fields and raise it to provide richer error information.

exceptions custom-exception error-handling
Python
class InsufficientFundsError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f"Withdrawal of ${amount} failed: balance ${balance} is insufficient")


def withdraw(balance, amount):
    if amount > balance:
        raise Insuffici…
13 0 Open
OOP & classes easy

How to Implement Rich Comparison Ordering in Python Classes

This code demonstrates how to implement rich comparison operators (like <, <=, >, >=, ==, !=) in a Python class by defining __lt__ and __eq__, enabling sorting and ordering of custom objects.

rich comparison sorting operators
Python
class Task:
    def __init__(self, priority, name):
        self.priority = priority
        self.name = name

    def __lt__(self, other):
        if not isinstance(other, Task):
            return NotImplemented
        return self.priority < other.priority

    def __eq__(self, other):
        if not isinstance(oth…
12 0 Open
Data pipelines & processing easy

Enrich Events with Geo IP Data in Python

Returns a copy of each event dictionary, enriched with a geo-location dict from a mock IP-to-geo lookup table, with a fallback for unknown IPs.

data-enrichment dictionaries pipelines
Python
import ipaddress


GEO_IP_DB = {
    "192.168.1.10": {"country": "US", "city": "New York", "lat": 40.7128, "lon": -74.0060},
    "10.0.0.5": {"country": "DE", "city": "Berlin", "lat": 52.5200, "lon": 13.4050},
    "172.16.0.8": {"country": "JP", "city": "Tokyo", "lat": 35.6762, "lon": 139.6503},
}

EVENTS = [
    {"id…
14 0 Open
Modern tooling easy

How to Create a Rich Console Progress Bar Mock in Python

This code uses Rich's Console and Progress API to build a simulated progress bar for a long-running task, updating progress and printing status messages.

rich progress-bar cli
Python
import time
from rich.console import Console
from rich.progress import Progress, BarColumn, TextColumn, PercentageColumn

console = Console()

def run_simulation():
    console.print("[bold cyan]Starting simulated task...[/bold cyan]")
    
    with Progress(
        TextColumn("[bold blue]{task.description}[/bold blu…
11 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.