Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

40 matches
Strings & text easy

Extract URLs from text with regex in Python

Uses a regular expression to find and print HTTP/HTTPS URLs from a block of text.

regex url text-processing
Python
import re

text = """
Visit https://www.example.com for docs.
Contact support@mysite.org.
Check http://localhost:8000/api or ftp://files.example.net.
"""

url_pattern = r'https?://[^\s]+'

urls = re.findall(url_pattern, text)

for url in urls:
    print(url)
14 0 Open
Errors & debugging easy

Catch RecursionError and Fail Gracefully in Python

Wrap a recursive function call in a try-except block to catch RecursionError and print a graceful failure message instead of crashing.

recursion exceptions error-handling
Python
def compute_factorial_recursive(n):
    """Compute factorial recursively, raising RecursionError for deep recursion."""
    if n == 0:
        return 1
    return n * compute_factorial_recursive(n - 1)


if __name__ == "__main__":
    try:
        result = compute_factorial_recursive(10000)
        print(f"Factorial c…
13 0 Open
Errors & debugging easy

Catch ValueError and print friendly message in Python

Wrap an int() call in a try/except block and print a friendly message when ValueError is raised.

error handling try except valueerror
Python
try:
    number = int("not_a_number")
except ValueError:
    print("That's not a valid number. Please enter digits only.")
13 0 Open
Errors & debugging easy

How to Build a Simple Debug Timer in Python

Create a context manager class to time the execution of a code block with a one-line printout.

debugging context-manager performance
Python
import time


class DebugTimer:
    """Context manager that times the execution of a code block."""

    def __init__(self, label="Operation"):
        self.label = label
        self.start_time = None

    def __enter__(self):
        self.start_time = time.perf_counter()
        return self

    def __exit__(self, e…
15 0 Open
Errors & debugging easy

How to Catch ValueError in Python (try except)

Handle invalid numeric input by catching ValueError in a try/except block and returning a friendly error message.

errors exception handling valueerror
Python
def parse_number(text):
    try:
        number = int(text)
        return f"Parsed number: {number}"
    except ValueError as error:
        return f"Error: '{text}' is not a valid number ({error})"


if __name__ == "__main__":
    examples = ["42", "hello", "3.14", "100"]
    for item in examples:
        print(pars…
11 0 Open
Errors & debugging easy

How to Handle ValueError Exceptions in Python

A beginner-friendly example showing how to catch ValueError and related exceptions with try-except blocks in Python.

exceptions valueerror try-except
Python
def divide_numbers(a, b):
    try:
        result = a / b
        return f"{a} / {b} = {result}"
    except ZeroDivisionError:
        return "Error: Cannot divide by zero."
    except TypeError:
        return "Error: Please provide numbers, not strings."
    except ValueError:
        return "Error: Invalid value de…
15 0 Open
Errors & debugging easy

How to Handle ValueError When Converting Strings to Integers in Python

Convert text to an integer with a try-except block that catches ValueError and prints beginner-friendly error messages.

valueerror try-except int
Python
def parse_number(text):
    """Convert text to an integer, showing beginner-friendly error handling."""
    try:
        number = int(text)
        print(f"Successfully parsed: {number}")
        return number
    except ValueError as e:
        print(f"Error: '{text}' is not a valid number.")
        print(f"Debuggin…
11 0 Open
Errors & debugging easy

How to Handle ValueError and Multiple Exceptions in Python

This code demonstrates try/except blocks for beginners, handling ZeroDivisionError, TypeError, and ValueError with two practical functions: dividing numbers and parsing strings to floats.

try-except valueerror exception-handling
Python
def divide_numbers(a, b):
    """Divide two numbers with error handling for beginners."""
    try:
        result = a / b
        print(f"{a} / {b} = {result}")
        return result
    except ZeroDivisionError:
        print(f"Error: Cannot divide {a} by zero!")
    except TypeError:
        print(f"Error: Both argu…
13 0 Open
Errors & debugging easy

How to Handle ValueError in Python (try except)

Learn to catch ValueError and other exceptions with try-except blocks in Python using practical division and string-to-float conversion examples.

try-except valueerror error-handling
Python
def divide_numbers(a, b):
    """Divide two numbers and handle ValueError safely."""
    try:
        result = a / b
        return f"{a} / {b} = {result}"
    except ZeroDivisionError:
        return "Error: Cannot divide by zero!"
    except TypeError:
        return "Error: Both inputs must be numbers!"


def parse…
13 0 Open
Errors & debugging easy

How to Handle ValueError with try-except in Python

Build a beginner-friendly division calculator that catches ValueError and ZeroDivisionError with try-except blocks.

error-handling try-except valueerror
Python
def get_number(prompt="Enter a number: "):
    while True:
        try:
            value = float(input(prompt))
            return value
        except ValueError:
            print("That's not a valid number. Please try again.")


def divide_numbers(a, b):
    try:
        result = a / b
        return result
    ex…
12 0 Open
Errors & debugging easy

How to Inspect Local Variables in an except Block in Python

Capture and print local variables at the moment an exception occurs using locals() inside an except block.

debugging exception-handling locals
Python
def risky_operation(value):
    try:
        result = 10 / value
        return result
    except ZeroDivisionError as e:
        local_vars = dict(locals())
        print(f"Error: {e}")
        print("Local variables at exception:")
        for key, val in local_vars.items():
            print(f"  {key} = {val}")
   …
13 0 Open
Errors & debugging easy

How to Use try except else finally in Python

Demonstrates the correct order of try/except/else/finally blocks in Python with a safe division function.

try-except error-handling flow-control
Python
def safe_divide(numerator, denominator):
    try:
        result = numerator / denominator
    except ZeroDivisionError:
        print("Error: Cannot divide by zero!")
    except TypeError:
        print("Error: Both arguments must be numbers!")
    else:
        print(f"Division successful: {numerator} / {denominator…
14 0 Open
Errors & debugging medium

Implement circuit breaker open after failures demo in Python

A minimal CircuitBreaker class that calls a function and automatically 'opens' after a set number of consecutive failures, blocking further calls with a RuntimeError.

circuit-breaker resilience error-handling
Python
import time
from datetime import datetime


class CircuitBreaker:
    def __init__(self, threshold=3):
        self.threshold = threshold
        self.failure_count = 0
        self.is_open = False

    def call(self, func, *args, **kwargs):
        if self.is_open:
            raise RuntimeError("Circuit is OPEN")
  …
12 0 Open
Errors & debugging easy

Split try except ValueError handler for beginners in Python

Demonstrates how to handle ValueError and ZeroDivisionError separately using try/except blocks, with beginner-friendly examples for parsing and division.

try-except valueerror zerodivisionerror
Python
def parse_number(text):
    try:
        number = int(text)
        return f"Parsed successfully: {number}"
    except ValueError as error:
        return f"Conversion failed: {error}"

def divide_numbers(dividend, divisor):
    try:
        result = dividend / divisor
        return f"Division result: {result}"
    e…
14 0 Open
Files & data medium

Chunk Large File Upload Simulation by Blocks in Python

A Python script reads a large binary file in fixed-size chunks and simulates a block-by-block upload with per-chunk SHA256 hashing.

file i/o chunking hashing
Python
import os
import hashlib
from pathlib import Path


def read_file_in_chunks(file_path, chunk_size=8196):
    """Yield chunks of a file as bytes."""
    with open(file_path, 'rb') as f:
        while chunk := f.read(chunk_size):
            yield chunk


def simulate_chunked_upload(file_path, chunk_size=8196):
    """S…
15 0 Open
Files & data medium

How to Use fcntl for Exclusive File Locking in Python

This code demonstrates how to acquire an exclusive advisory lock on a file using fcntl.flock with a non-blocking flag, simulate work, then release the lock.

fcntl file-locking flock
Python
import fcntl
import os
import tempfile
import time

def acquire_exclusive_lock(filepath):
    fd = os.open(filepath, os.O_RDWR | os.O_CREAT)
    try:
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        print(f"Exclusive lock acquired on {filepath}")
        time.sleep(1)  # Simulate work while holding the l…
12 0 Open
OOP & classes easy

How to define a custom exception class in Python with an error code attribute

Create a custom exception class with extra attributes like an error code, then raise and catch it in a try/except block.

exceptions classes error-handling
Python
class UserNotFoundError(Exception):
    def __init__(self, user_id, error_code=404):
        self.user_id = user_id
        self.error_code = error_code
        super().__init__(f"User with ID {user_id} was not found (error code: {error_code})")

def find_user(user_id, users_db):
    if user_id not in users_db:
      …
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 Filter Blocked Words in Python

Scans input text against a moderation blocklist, returning blocked terms and their counts.

moderation blocklist security
Python
MODERATION_BLOCKLIST = {"spam", "scam", "fraud", "phishing", "malware", "abuse"}

def scan_text(text: str) -> dict:
    normalized = text.lower()
    words = normalized.replace(".", " ").replace(",", " ").replace("!", " ").replace("?", " ").split()
    
    found_terms = []
    for word in words:
        if word in MO…
12 0 Open
Automation & scripting easy

How to Update a Hosts File to Block Distractions in Python

This script updates a local hosts file (or a demo file) by adding or updating entries to block distracting websites like Facebook and Twitter.

hosts-file automation blocking
Python
from pathlib import Path

def update_hosts(entries):
    """
    Add or update blocking entries in the hosts file.
    Uses a local demo file by default to avoid system changes.
    """
    hosts_path = Path("demo_hosts.txt")
    
    # Create demo file if it doesn't exist
    if not hosts_path.exists():
        hosts…
11 0 Open
Automation & scripting easy

How to Write an IP Block List to hosts.deny in Python

This Python script validates a list of IP addresses and CIDR ranges, then writes them to a hosts.deny file to block connections at the TCP wrapper level.

hosts.deny ip-block ipaddress
Python
from ipaddress import ip_network

def write_hosts_deny(ip_list, output_file="hosts.deny"):
    with open(output_file, "w") as f:
        for ip in ip_list:
            try:
                ip_network(ip)
                f.write(f"ALL: {ip}\n")
            except ValueError:
                continue
    print(f"Written…
14 0 Open
Automation & scripting medium

How to check Python files for common coding mistakes

Walks a directory tree parsing each .py file with ast, reporting empty functions, bare try blocks, too many parameters, and empty classes.

ast linting code-quality
Python
import ast
import os
import sys

def check_file(filepath):
    try:
        with open(filepath) as f:
            code = f.read()
        tree = ast.parse(code, filename=filepath)
    except SyntaxError as e:
        print(f"{filepath}: SyntaxError: {e.msg}")
        return
    
    issues = []
    for node in ast.wal…
42 0 Open
Modern tooling easy

Mock pip-compile to Resolve Requirements in Python

A mock function that mimics pip-compile by converting a requirements.in file into pinned, locked package versions.

pip-tools requirements mock
Python
import subprocess
import tempfile
from pathlib import Path


def compile_requirements_mock(requirements_in: str) -> str:
    """Mock pip-compile: resolve a simple requirements.in into a locked format."""
    lines = [line.strip() for line in requirements_in.splitlines() if line.strip() and not line.startswith("#")]
  …
12 0 Open
Concurrency & performance medium

How to Demonstrate the GIL with Python Threads vs Processes

Measure and compare wall-clock time for CPU-bound work using Python threads (limited by the GIL) versus multiprocessing (which bypasses the GIL).

gil threading multiprocessing
Python
import threading
import multiprocessing
import time
import os


def cpu_heavy(n):
    return sum(i * i for i in range(n))


def run_threads(n):
    threads = [threading.Thread(target=cpu_heavy, args=(n,)) for _ in range(2)]
    start = time.perf_counter()
    for t in threads:
        t.start()
    for t in threads:
 …
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.