Reference library

Python Code Samples

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

38 matches
Strings & text easy

Build a Secure Password Strength Checker in Python

A Python function that evaluates password strength based on length and character diversity, returning Weak, Moderate, or Strong.

password security regex
Python
import re

def password_strength(password: str) -> str:
    score = 0
    if len(password) >= 8:
        score += 1
    if re.search(r'[a-z]', password):
        score += 1
    if re.search(r'[A-Z]', password):
        score += 1
    if re.search(r'\d', password):
        score += 1
    if re.search(r'[!@#$%^&*(),.?":…
55 0 Open
Lists & loops easy

How to Find the Mode in a Python List

Find the most frequent value (mode) in a Python list using the collections.Counter class, handling empty lists and ties.

mode counter frequency
Python
from collections import Counter

def find_mode(numbers):
    if not numbers:
        return None
    counts = Counter(numbers)
    max_count = max(counts.values())
    modes = [num for num, count in counts.items() if count == max_count]
    return modes[0] if len(modes) == 1 else modes

if __name__ == "__main__":
    …
14 0 Open
Files & data easy

How to Write Bytes to a File in Python with 'wb'

Write a bytearray buffer to a binary file using Python's open() in 'wb' mode, then read it back to confirm the data.

bytes file-writing binary-files
Python
data = bytearray([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64])

with open("output.bin", "wb") as f:
    f.write(data)

with open("output.bin", "rb") as f:
    content = f.read()

print(f"Written {len(data)} bytes: {content}")
print(f"As string: {content.decode('ascii')}")
13 0 Open
OOP & classes easy

How to Create a Data Helper Class in Python with OOP

A complete OOP example with User, Post, and Blog classes that manage data relationships and provide clear helper methods.

oop classes data-modeling
Python
class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.posts = []

    def create_post(self, title, content):
        post = Post(title, content, self)
        self.posts.append(post)
        return post

    def get_post_count(self):
        return len(self.p…
12 0 Open
OOP & classes easy

Python Adapter Class: Wrap Legacy Interface

Convert a legacy system's interface into a modern one using the Adapter pattern in Python, translating method calls and data formats.

adapter design-pattern oop
Python
class LegacySystem:
    """Legacy interface - old method names and parameter format."""
    def query_employee_info(self, emp_id, emp_name):
        return f"Legacy: {emp_id} - {emp_name}"

    def update_employee_department(self, emp_id, department_code):
        return f"Legacy: Updated {emp_id} to dept {department_…
13 0 Open
AI & LLM integration patterns easy

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.

llm dataclass openai
Python
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…
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
AI & LLM integration patterns easy

How to Parse Chat Completion JSON in Python

Parse a mock OpenAI chat completion JSON response into a clean dictionary with content, finish reason, and model.

json openai chat-completion
Python
import json

def parse_chat_response(raw: str) -> dict:
    data = json.loads(raw)
    choice = data["choices"][0]
    return {
        "content": choice["message"]["content"],
        "finish_reason": choice["finish_reason"],
        "model": data["model"],
    }

if __name__ == "__main__":
    mock_response = '''
  …
14 0 Open
AI & LLM integration patterns easy

How to Parse JSON from LLM Model Output Fence in Python

Extract and parse a JSON object from a language model's output that may be wrapped in triple-backtick fences with an optional language tag.

json llm parsing
Python
import json
import re

def parse_json_from_fence(text):
    """
    Extract JSON object from a model output that may be wrapped in
    triple-backtick fences with optional language tag.
    """
    # Match content inside
12 0 Open
AI & LLM integration patterns easy

JSON Mode Prompt Schema Output in Python

Extract a user object to JSON with explicit schema keys, ready for LLM JSON-mode prompts.

json schema llm
Python
import json
from typing import Any, Dict


def extract_user_as_json(user: Dict[str, Any]) -> str:
    """Extract a user object and return it as JSON using explicit schema keys."""
    schema_fields = ("id", "name", "email", "is_active")
    user_subset = {key: user[key] for key in schema_fields if key in user}
    ret…
13 0 Open
Automation & scripting easy

How to Mock a Whisper API Transcription Stub in Python

Simulate an OpenAI Whisper-style transcription response with a dataclass request model and a mock function that returns structured audio transcription output.

mock whisper api-stub
Python
import json
from dataclasses import dataclass
from typing import Optional

@dataclass
class AudioRequest:
    file_path: str
    language: Optional[str] = None

    def to_api_payload(self) -> dict:
        return {"file": self.file_path, "language": self.language}

def mock_whisper_transcribe(payload: dict) -> dict:
…
15 0 Open
Automation & scripting easy

Resize Disk Partitions in Python (Mock Script)

A mock disk partition resize script that uses dataclasses to model partitions, validate new sizes, and output the updated layout as JSON.

disk partition dataclass
Python
#!/usr/bin/env python3
"""Mock script to demonstrate disk partition resize logic."""
import json
from dataclasses import dataclass
from typing import Dict


@dataclass
class Partition:
    name: str
    size_gb: int
    mount_point: str

    def to_dict(self) -> Dict[str, object]:
        return {
            "name": …
16 0 Open
Modern tooling easy

How to Mock isort Output to Test Import Sorting in Python

Uses isort with check mode and a unittest mock to verify whether a Python source string has correctly sorted imports.

isort import-sorting mock
Python
import isort
from unittest.mock import patch

code = """
import os
import sys
import json
import pathlib
"""

def check_imports_sorted(code_str):
    with patch("isort.api.output") as mock_output:
        isort.code(code_str, check=True, show_diff=True)
        return mock_output.called

if __name__ == "__main__":
   …
10 0 Open
Modern tooling easy

How to Parse and Extract Nested Data in Python

Load JSON files with Path and recursively extract values by key from nested Python structures using modern typing and standard library.

json pathlib recursion
Python
import json
from pathlib import Path
from typing import Any, Dict, List, Union

def load_data(filepath: Union[str, Path]) -> Union[Dict[str, Any], List[Any]]:
    """Load JSON data from a file with modern Path handling."""
    path = Path(filepath)
    if not path.exists():
        raise FileNotFoundError(f"File not f…
12 0 Open
Testing & modern typing easy

Format Data with Type Hints in Python

Build a validated person dict with modern type hints and optional list handling.

type-hints typing data-formatting
Python
from typing import Any, Dict, List, Optional, Union

JsonValue = Union[str, int, float, bool, None, List["JsonValue"], Dict[str, "JsonValue"]]

def format_person(name: str, age: int, hobbies: Optional[List[str]] = None) -> Dict[str, Any]:
    """Build a person dict with validated typing."""
    if not name or age < 0:…
12 0 Open
Testing & modern typing easy

How to Filter Data in Python with Type Hints

A reusable filter_data helper uses optional predicates and numeric bounds with modern Python type hints.

filtering type-hints generics
Python
from typing import Iterable, TypeVar, Callable, Any

T = TypeVar("T")

def filter_data(
    items: Iterable[T],
    predicate: Callable[[T], bool] | None = None,
    *,
    min_value: float | None = None,
    max_value: float | None = None,
) -> list[T]:
    """Filter items by predicate and/or numeric bounds."""
    r…
11 0 Open
Testing & modern typing easy

How to Parse Data with Type Hints in Python

A beginner-friendly helper that parses simple dictionary- or list-like strings into typed Python structures using modern typing annotations.

type-hints parsing typing
Python
from typing import Any, Dict, List, Union


def parse_data(raw: str) -> Union[Dict[str, Any], List[Any], str]:
    """Parse a simple string into structured data using type hints."""
    cleaned = raw.strip()
    
    if not cleaned:
        return {}
    
    if cleaned.startswith("{") and cleaned.endswith("}"):
     …
11 0 Open
Testing & modern typing easy

How to mark known bugs with pytest xfail in Python

Use @pytest.mark.xfail to mark tests that are expected to fail due to known bugs, with optional strict mode to control pass/fail behavior.

pytest testing xfail
Python
import pytest


def divide(a: int, b: int) -> float:
    if b == 0:
        raise ZeroDivisionError("Cannot divide by zero")
    return a / b


@pytest.mark.xfail(reason="Known bug: division returns int instead of float", strict=False)
def test_divide_integer_division():
    result = divide(10, 4)
    assert isinstanc…
16 0 Open
System design patterns easy

How to Build an MVP Presenter View Mock in Python

A minimal MVP (Model-View-Presenter) mock showing a Presenter controlling a SlideDeck model with slide navigation and typed state via dataclasses.

dataclasses mvp design-patterns
Python
from dataclasses import dataclass, field
from typing import List


@dataclass
class SlideDeck:
    title: str
    slides: List[str] = field(default_factory=list)
    current_index: int = 0

    def next_slide(self) -> str:
        if self.current_index < len(self.slides) - 1:
            self.current_index += 1
      …
13 0 Open
System design patterns easy

Python MVC Pattern Example (Model-View-Controller)

A minimal, runnable Model-View-Controller (MVC) example in pure Python that separates data, presentation, and logic.

mvc design-pattern architecture
Python
class Model:
    def __init__(self):
        self.data = {"title": "Initial Title", "content": "Initial Content"}

    def get_data(self):
        return self.data

    def update_data(self, title=None, content=None):
        if title:
            self.data["title"] = title
        if content:
            self.data["c…
15 0 Open
Observability & SRE easy

How to Model Span Events in Python

Define a Span class with timestamped milestone events and a completion marker to track operation lifecycle.

observability dataclasses tracing
Python
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import List


class SpanStatus(Enum):
    STARTED = "started"
    COMPLETED = "completed"


@dataclass
class SpanEvent:
    name: str
    timestamp: float = field(default_factory=time.time)
    attributes: dict = field(default_facto…
14 0 Open
Microservices patterns easy

How to Use the Adapter Pattern to Mock a Legacy System in Python

This code demonstrates the Adapter pattern, allowing a modern interface to interact with a legacy system by wrapping its outdated method.

adapter-pattern design-patterns legacy
Python
class LegacySystem:
    def legacy_method(self, data):
        return f"Legacy processed: {data}"

class ModernInterface:
    def process(self, data):
        raise NotImplementedError

class Adapter(ModernInterface):
    def __init__(self, legacy):
        self.legacy = legacy

    def process(self, data):
        re…
13 0 Open
Microservices patterns easy

Strangler Fig Migration Pattern in Python

Gradually reroute calls from a legacy service to a modern replacement using a runtime switch and feature detection.

migration facade microservices
Python
from dataclasses import dataclass

@dataclass
class PaymentService:
    def process(self, amount: float) -> str:
        return f"Legacy processed ${amount:.2f}"

class StranglerFig:
    def __init__(self):
        self._new_service = None

    def attach_new(self, service):
        self._new_service = service

    de…
14 0 Open
Big data & Spark easy

Modeling a Hive Metastore Table Schema in Python

A dataclass that mimics a Hive metastore table schema—columns, partition keys, storage format, and location—with helper methods for description and mutation.

hive dataclass metastore
Python
from dataclasses import dataclass, field
from typing import Dict, List, Optional


@dataclass
class HiveTable:
    """Simple mock of a Hive metastore table schema."""
    name: str
    database: str = "default"
    columns: List[Dict[str, str]] = field(default_factory=list)
    partition_keys: List[Dict[str, str]] = f…
13 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.