Reference library

Python Code Samples

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

7 matches
Functions & basics easy

Build a Context Manager in Python with contextlib.contextmanager

Create a reusable context manager that safely opens and closes files using the contextlib contextmanager decorator.

context manager contextlib file handling
Python
from contextlib import contextmanager

@contextmanager
def managed_file(filename, mode='r'):
    """Context manager that opens and closes a file safely."""
    file = open(filename, mode)
    yield file
    file.close()

if __name__ == "__main__":
    # Write a sample file
    with managed_file("sample.txt", "w") as f…
14 0 Open
OOP & classes easy

How to Build a Context Manager Class in Python

Create a reusable context manager class that opens and automatically closes resources using the with statement.

context-manager with-statement resource-management
Python
class FileResource:
    def __init__(self, filename, mode='r'):
        self.filename = filename
        self.mode = mode
        self.file = None

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

    def __exit__(self, exc_type, exc_value, traceback):
        if se…
12 0 Open
Algorithms & data structures easy

Find k Closest Points to Origin in Python

Sorts a list of (x, y) point tuples by their Euclidean distance from the origin and returns the k nearest points.

sorting euclidean-distance geometry
Python
import math

def k_closest(points, k):
    points.sort(key=lambda p: math.sqrt(p[0]**2 + p[1]**2))
    return points[:k]

if __name__ == "__main__":
    points = [(1, 2), (3, 4), (-1, 0), (5, 5), (0, 1)]
    k = 3
    result = k_closest(points, k)
    print(f"Original points: {points}")
    print(f"K closest points (k…
12 0 Open
Algorithms & data structures easy

How to Find the Nearest Value to a Target in a Sorted List in Python

Use bisect to binary-search a sorted list and return the element closest to a target value.

bisect binary-search sorted-list
Python
import bisect

def nearest_value(sorted_list, target):
    if not sorted_list:
        return None
    pos = bisect.bisect_left(sorted_list, target)
    if pos == 0:
        return sorted_list[0]
    if pos == len(sorted_list):
        return sorted_list[-1]
    before = sorted_list[pos - 1]
    after = sorted_list[po…
15 0 Open
Comprehensions & generators easy

How to Close a Generator and Handle GeneratorExit in Python

This Python code demonstrates how to explicitly close a generator using the close() method and handle the GeneratorExit exception through a finally block to run cleanup logic.

generators generator-exit close
Python
def countdown(n):
    try:
        while n > 0:
            yield n
            n -= 1
    finally:
        print(f"Generator closed after countdown completed")


if __name__ == "__main__":
    gen = countdown(5)
    print(next(gen))
    print(next(gen))
    gen.close()
    print("Generator closed explicitly")
12 0 Open
AI & LLM integration patterns easy

How to Build a Simple Semantic Cache for Similar Prompts in Python

Mock a semantic cache that finds the closest matching prompt using word-overlap similarity and returns cached results above a threshold.

semantic cache prompt matching llm
Python
prompt_cache = [
    "What is the capital of France?",
    "How does recursion work?",
    "Best practices for Python logging?",
    "Explain binary search in one line.",
    "How to reverse a string in Python?"
]

def normalize(text):
    return " ".join(text.lower().split())

def similarity(a, b):
    a_words = set(…
14 0 Open
Automation & scripting easy

Port Scan Localhost Common Ports in Python

Scan common localhost ports (HTTP, HTTPS, SSH, FTP, and more) with a fast socket-based Python script that prints an open/closed status table.

socket port-scanning network
Python
import socket
from datetime import datetime

COMMON_PORTS = {
    80: "HTTP", 
    443: "HTTPS", 
    22: "SSH", 
    21: "FTP", 
    25: "SMTP",
    3306: "MySQL",
    5432: "PostgreSQL"
}

def scan_port(port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(0.1)
    try:
        resu…
12 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.