Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Assert Preconditions with Descriptive Messages in Python
Use Python's assert statement with a custom message to validate function preconditions and fail fast with clear diagnostics.
def divide(dividend, divisor):
assert divisor != 0, f"Divisor must be non-zero, got {divisor!r}"
return dividend / divisor
if __name__ == "__main__":
print(divide(10, 2))
try:
divide(10, 0)
except AssertionError as e:
print(f"AssertionError: {e}")
How to Assert an Invariant After a Complex Transformation in Python
Use assert to verify that a multi-step transformation preserves a mathematical invariant, catching regressions early.
def transform_value(value):
"""Apply several transformations to a value."""
doubled = value * 2
shifted = doubled + 10
normalized = shifted / 2
return int(normalized)
def assert_invariant(value):
"""Assert that the transformation preserves a key invariant."""
original = value
transform…
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.
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…
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.
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…
How to Configure Python Logging with File Rotation
A complete demo that sets up a logger with a rotating file handler, writes several log entries, and shows the contents of the current log file.
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger("rotating_logger")
logger.setLevel(logging.DEBUG)
file_handler = RotatingFileHandler(
"app.log",
maxBytes=100,
backupCount=3
)
file_handler.setFormatter(
logging.Formatter("%(asctime)s - %(levelname)s - %(messa…
How to Debug Print Behind a DEBUG Environment Flag in Python
Create a debug_print function that only outputs when the DEBUG environment variable is set to a truthy value like 1, true, yes, or on.
import os
def debug_print(*args, **kwargs):
"""Print only when DEBUG environment variable is set to a truthy value."""
if os.environ.get("DEBUG", "").lower() in ("1", "true", "yes", "on"):
print(*args, **kwargs)
if __name__ == "__main__":
# Example usage: run as `DEBUG=1 python script.py` to se…
How to Detect the Recursion Limit in Python with sys.getrecursionlimit
This Python code recursively calls itself, printing the current recursion depth and the recursion limit from sys.getrecursionlimit, and catches the RecursionError when the limit is hit.
import sys
def recurse(depth=0):
print(f"Depth: {depth}, Recursion limit: {sys.getrecursionlimit()}")
return recurse(depth + 1)
if __name__ == "__main__":
try:
recurse()
except RecursionError:
print("Recursion limit reached!")
print(f"Final recursion limit: {sys.getrecursionli…
How to Dump a Debugging Repr for Unknown Types in Python
Build a fallback repr that shows dataclass fields or object attributes for any value, handy when debugging unknown types.
import dataclasses
from typing import Any
@dataclasses.dataclass
class Sample:
name: str
values: list[int]
def dump_repr(obj: Any) -> str:
"""Return a concise but complete repr for debugging unknown types."""
if dataclasses.is_dataclass(obj):
fields = ", ".join(
f"{field.name}={…
How to Emit Deprecation Warnings in Python
Use the warnings module to mark legacy classes and methods as deprecated, letting users know to switch to newer APIs.
import warnings
class OldAPI:
def __init__(self):
warnings.warn(
"OldAPI is deprecated; use NewAPI instead.",
DeprecationWarning,
stacklevel=2,
)
self.data = []
def add(self, item):
warnings.warn(
"OldAPI.add() is deprecated; us…
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.
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…
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.
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}")
…
How to Log Exceptions with traceback.format_exc in Python
Capture and log a full traceback string when an exception occurs using Python's traceback.format_exc() and logging module.
import traceback
import logging
def risky_operation(value):
return 10 / value
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
def main():
try:
result = risky_operation(0)
print(f"Result: {result}")
except ZeroDivisionError:
error_msg =…
How to Measure Python Stack Depth with inspect.stack()
Measure the current call stack depth in Python using the inspect module to understand recursion depth and debug execution context.
import inspect
def stack_depth():
return len(inspect.stack())
def recursive_function(n):
if n == 0:
print(f"Base case reached. Stack depth: {stack_depth()}")
return
recursive_function(n - 1)
if __name__ == "__main__":
print(f"Initial stack depth: {stack_depth()}")
recursive_funct…
How to Record Last N Errors with a Ring Buffer in Python
Use collections.deque with maxlen to keep only the most recent N error messages while discarding older entries automatically.
import collections
class ErrorRecorder:
def __init__(self, size):
self.buffer = collections.deque(maxlen=size)
def record_error(self, message):
self.buffer.append(message)
def get_errors(self):
return list(self.buffer)
if __name__ == "__main__":
recorder = ErrorRecorder(3)
…
How to Serialize an Exception to a JSON-Safe Dict in Python
Convert any Python exception into a JSON-safe dictionary with type, message, and the last few traceback lines for logging.
import json
import traceback
from typing import Any
def exception_to_dict(exc: Exception) -> dict[str, Any]:
"""Convert an exception into a JSON-safe dictionary."""
return {
"type": type(exc).__name__,
"message": str(exc),
"traceback": traceback.format_exc().strip().split("\n")[-3:],
…
How to Use pdb.post_mortem in Python
Automatically enter the Python debugger at the exact point where an uncaught exception occurred, allowing interactive inspection of the crash site.
import pdb
import sys
def divide(a, b):
return a / b
def main():
try:
result = divide(10, 0)
print(f"Result: {result}")
except Exception:
# Enter post-mortem debugging when an uncaught exception occurs
pdb.post_mortem(sys.exc_info()[2])
if __name__ == "__main__":
main…
How to Use the breakpoint() Function for Interactive Debugging in Python
Insert a breakpoint() call into your code to drop into an interactive debugger session where you can inspect variables and step through execution.
def calculate_total(prices, discount=0):
"""Calculates total price with optional discount."""
subtotal = sum(prices)
breakpoint() # Interactive debugging session starts here
final_total = subtotal * (1 - discount)
return final_total
if __name__ == "__main__":
items = [25.50, 13.25, 9.99, 5.7…
Log to stderr with Python logging basicConfig
Configure Python's logging module to send all log messages to standard error (stderr) instead of the default stderr, with a readable timestamped format.
import logging
def main():
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s — %(name)s — %(levelname)s — %(message)s",
stream=__import__("sys").stderr,
)
logger = logging.getLogger("example")
logger.debug("Debug message")
logger.info("Info message")
logger.…
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.
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…
Use pprint for Nested Structure Debug Output in Python
Pretty-print nested dictionaries and lists with pprint for readable, organized debug output.
from pprint import pprint
def build_nested_structure():
"""Create a sample nested data structure for demonstration."""
return {
"project": "DataPipeline",
"config": {
"inputs": ["raw_1.json", "raw_2.json"],
"processing": {
"steps": ["clean", "transform",…
Validate try except ValueError handler for beginners — errors debugging
Learn how to validate user input and handle division errors safely using try/except with ValueError and ZeroDivisionError in Python.
def divide_numbers(a, b):
"""Divide two numbers, catching division by zero and value errors."""
try:
result = a / b
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
return None
except TypeError:
print("Error: Both arguments must be numbers!")
retu…
How to Mock OpenTelemetry Tracer Setup in Python
Set up a mock OpenTelemetry tracer with an in-memory span exporter to capture spans for testing and debugging.
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
def setup_tracer():
provider = TracerProvider()
exporter = InMemorySpanExpo…
How to Mock an OTLP HTTP Endpoint in Python
This code implements a lightweight HTTP server that accepts OTLP/HTTP trace exports, stores spans by trace ID, and exposes them via a simple GET endpoint for debugging.
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from collections import defaultdict
class TraceHandler(BaseHTTPRequestHandler):
traces = defaultdict(list)
def do_POST(self):
if self.path == "/v1/traces":
length = int(self.headers.get("Content-Length", 0))
…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.