Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Validate List Data in Python
A beginner-friendly validation helper that checks if data is a list, enforces minimum length, and optionally verifies item types with clear error messages.
def validate_data(data, expected_types=None, min_length=1):
"""Validate that data is a non-empty list and optionally check item types."""
if not isinstance(data, list):
return False, f"Expected a list, got {type(data).__name__}"
if len(data) < min_length:
return False, f"List must have…
How to Validate Function Arguments in Python
Shows how to manually check argument types and values in a Python function, raising clear TypeError and ValueError messages.
def calculate_area(length: float, width: float) -> float:
"""Calculate the area of a rectangle with manual type validation."""
if not isinstance(length, (int, float)) or isinstance(length, bool):
raise TypeError(f"length must be a number, got {type(length).__name__}")
if not isinstance(width, (int,…
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.
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…
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.
try:
number = int("not_a_number")
except ValueError:
print("That's not a valid number. Please enter digits only.")
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 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 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.
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…
How to Handle ValueError with try except in Python
Shows a beginner-friendly try/except pattern that catches ValueError when converting text to an integer, prints a helpful message, and returns None instead of crashing.
def parse_number(text):
try:
return int(text)
except ValueError:
print(f"ValueError: '{text}' is not a valid integer.")
return None
if __name__ == "__main__":
user_input = "abc"
result = parse_number(user_input)
print(f"Parsing '{user_input}' returned: {result}")
vali…
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 Return Success or Error as a Tuple in Python (Result Type Pattern)
Use a (bool, value) tuple as a lightweight Result type to return either a successful result or a descriptive error message from a Python function.
def divide(dividend: float, divisor: float) -> tuple[bool, float | str]:
"""Return (True, result) on success, (False, error_message) on failure."""
if divisor == 0:
return False, "Error: Division by zero"
return True, dividend / divisor
if __name__ == "__main__":
# Success case
success, r…
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 Test Exceptions in Python with pytest.raises
Learn the pytest.raises pattern to assert that specific exceptions are raised and validate their messages.
import pytest
def divide(a: int, b: int) -> float:
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def test_divide_by_zero_raises():
with pytest.raises(ValueError, match="Cannot divide by zero"):
divide(10, 0)
def test_divide_by_zero_raises_exact_match():
with py…
How to Validate Input and Raise TypeError in Python
Define a function that checks its argument type and raises a TypeError early with a clear message when given a non-number.
def validate_number(value):
if not isinstance(value, (int, float)):
raise TypeError(f"Expected a number, got {type(value).__name__}")
return value * 2
if __name__ == "__main__":
try:
print(validate_number(5))
print(validate_number("hello"))
except TypeError as e:
print(…
How to Validate JSON in Python and Catch JSONDecodeError
A robust Python function that attempts to parse JSON strings and returns a boolean plus either the parsed data or a descriptive error message when decoding fails.
import json
def validate_json(json_string):
"""Try to parse JSON, return (is_valid, data_or_error)."""
try:
data = json.loads(json_string)
return True, data
except json.JSONDecodeError as e:
return False, f"Invalid JSON: {e}"
if __name__ == "__main__":
test_inputs = [
…
How to catch ValueError in Python and print a friendly message
This code defines a function that safely converts text to an integer, catches ValueError, and prints a friendly message instead of crashing.
def parse_number(text):
try:
return int(text)
except ValueError:
print("Oops! That's not a valid number.")
return None
if __name__ == "__main__":
result = parse_number("abc")
if result is None:
print("Parsing failed.")
else:
print(f"Parsed value: {result}")
How to handle ZeroDivisionError in Python
Wrap a division operation in try/except to return None or a friendly message instead of crashing when dividing by zero.
def safe_divide(a, b):
"""Return a/b if possible, else None when dividing by zero."""
try:
return a / b
except ZeroDivisionError:
return None
def safe_divide_with_message(a, b):
"""Return a how-to message on divide-by-zero error."""
try:
return a / b
except ZeroDivisio…
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.…
Automatically Highlight Data Validation Errors Inside Excel Files in Python
Load an Excel file with openpyxl, iterate over cells, and highlight invalid data (empty, negative) with a red fill and error message.
import openpyxl
from openpyxl.styles import PatternFill
from pathlib import Path
def highlight_validation_errors(filepath: str, output_path: str = None):
wb = openpyxl.load_workbook(filepath)
red_fill = PatternFill(start_color="FF0000", end_color="FF0000", fill_type="solid")
for sheet in wb.worksheet…
Split a String into Multiple Lines by Width in Python
Demonstrates a word-wrap algorithm that splits a message into rows without exceeding a maximum width.
def split_message(text, max_width):
words = text.split()
rows = []
current_row = []
for word in words:
if len(" ".join(current_row + [word])) > max_width:
rows.append(" ".join(current_row))
current_row = [word]
else:
current_row.append(word)
if …
How to Build a System-User-Assistant Message List in Python
Use dataclasses to model a chat conversation and build the system/user/assistant message list expected by LLM APIs.
from dataclasses import dataclass, field
from typing import List
@dataclass
class Message:
role: str
content: str
@dataclass
class Conversation:
messages: List[Message] = field(default_factory=list)
def add_system(self, content: str) -> None:
self.messages.append(Message(role="system", con…
How to Mock OpenAI Tool Call Messages in Python
Create an assistant message with a function tool call in OpenAI's chat format, useful for testing and mocking.
from openai import OpenAI
def mock_tool_call(tool_name: str, arguments: dict) -> dict:
"""Simulate a tool call message in OpenAI style."""
return {
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_" + "a1b2c3d4e5f6",
"type…
How to Serialize Chat Messages to a JSON File in Python
Writes a list of chat message dicts to a JSON file with metadata like export time and message count.
import json
from pathlib import Path
from datetime import datetime
def serialize_messages(messages, output_path):
data = {
"exported_at": datetime.now().isoformat(),
"count": len(messages),
"messages": messages
}
Path(output_path).write_text(
json.dumps(data, indent=2, ensu…
How to Validate JSON Output Against a Dict Schema in Python
Validate JSON-like data against a simple dict schema with type checking and descriptive error messages using only the Python standard library.
from typing import Dict, Any, List, Union
def validate_json(data: Any, schema: Dict[str, str]) -> List[str]:
"""
Validate JSON-like data against a simple dict schema.
Schema format: {field_name: expected_type} where type is one of:
'str', 'int', 'float', 'bool', 'list', 'dict', 'any'
Returns list …
How to randomly assign a prompt variant to each key in Python
Randomly pick one variant from a list for each prompt key, useful for A/B testing message variations.
import random
def assign_prompt_variant(prompts: dict[str, list[str]]) -> dict[str, str]:
"""Assign a random prompt variant to each prompt key."""
return {key: random.choice(variants) for key, variants in prompts.items()}
if __name__ == "__main__":
prompt_bank = {
"greeting": ["Hello!", "Hi there…
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.