Reference library

Python Code Samples

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

107 matches
Data pipelines & processing easy

How to Safely Coerce Strings to Numbers in Python

A safe conversion function that turns strings into integers or floats, returning a fallback value when conversion fails.

type-conversion robust-parsing data-cleaning
Python
import math

def to_number(value, fallback=None):
    """Safely coerce a string to int or float, returning fallback on failure."""
    if isinstance(value, (int, float)):
        return value
    try:
        # Try int first for clean whole numbers
        return int(value)
    except (ValueError, TypeError):
        …
12 0 Open
Git + Python easy

How to Run Git Commands from Python with subprocess

This helper runs `git status --short` and `git log --oneline` from Python, captures their output, and returns readable strings with error handling for non-repo directories.

git subprocess automation
Python
import subprocess


def git_status():
    """Return a short, human-readable git status."""
    try:
        output = subprocess.run(
            ["git", "status", "--short"],
            capture_output=True,
            text=True,
            check=True,
        ).stdout.strip()
        return output if output else "W…
13 0 Open
Modern tooling easy

Data Conversion Helper Functions in Python

A set of beginner-friendly helper functions to convert between JSON strings and Python data, parse dates, and read/write files using pathlib.

json datetime pathlib
Python
from datetime import datetime
from pathlib import Path
import json

def to_json(data, indent=2):
    """Convert Python data to pretty-printed JSON string."""
    return json.dumps(data, indent=indent, default=str)

def from_json(json_string):
    """Parse JSON string back into Python data."""
    return json.loads(jso…
12 0 Open
Testing & modern typing easy

How to Convert Strings to Types in Python Using TypeVar

A beginner-friendly helper that converts a string to int, float, bool, or str with type hints and graceful failure handling.

typing type-hints conversion
Python
from typing import TypeVar, Optional

T = TypeVar("T")

def convert_data(value: str, target_type: type[T]) -> Optional[T]:
    """Convert string value to target type; return None on failure."""
    try:
        if target_type is int:
            return int(value)
        elif target_type is float:
            return f…
14 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 medium

How to Test Properties with Random Inputs in Python

Write a simple property-based test in Python using random string generation to verify that string invariants like reverse-twice identity and uppercase idempotence always hold.

property-based-testing random testing
Python
import random
import string


def generate_random_string(length: int) -> str:
    """Generate a random alphanumeric string of given length."""
    chars = string.ascii_letters + string.digits
    return "".join(random.choice(chars) for _ in range(length))


def reverse_twice_is_identity(s: str) -> bool:
    """Propert…
12 0 Open
Testing & modern typing medium

How to Use Hypothesis Strategies for Lists of Text in Python

Generate random lists of non-empty strings with Hypothesis and verify that joining them with a comma-and-space separator meets expected length and containment invariants.

hypothesis property-based-testing strategies
Python
from hypothesis import given, strategies as st
from hypothesis import example


@given(st.lists(st.text(min_size=1, max_size=10), min_size=1, max_size=5))
def test_joined_string_length(items):
    """Each text is non-empty; a joined string should be at least as long
    as the number of items (separator adds character…
13 0 Open
API design & gRPC easy

Convert Protobuf to JSON and Dict in Python

Provides static helper methods to convert between protobuf messages, JSON strings, and Python dictionaries using the google.protobuf library.

protobuf json grpc
Python
from google.protobuf.json_format import MessageToJson, Parse
import json


class DataConverter:
    """Helper class to convert between protobuf messages and common formats."""

    @staticmethod
    def to_json(message, indent=2):
        """Convert a protobuf message to JSON string."""
        return MessageToJson(me…
17 0 Open
Streaming & messaging easy

How to Serialize and Deserialize JSON Event Payloads in Python

Define an EventPayload class with custom to_json and from_json methods to convert event objects to JSON strings and back, using datetime parsing.

json serialization datetime
Python
import json
from datetime import datetime


class EventPayload:
    def __init__(self, event_id, event_type, timestamp, data):
        self.event_id = event_id
        self.event_type = event_type
        self.timestamp = timestamp
        self.data = data

    def to_json(self):
        return json.dumps({
          …
12 0 Open
Caching & Redis easy

Cache Data in Redis with Python

A beginner-friendly Redis cache helper that stores JSON strings with a TTL and retrieves them with the redis-py client.

redis cache ttl
Python
import redis


class DataCache:
    def __init__(self, host="localhost", port=6379, db=0):
        self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)

    def cache_data(self, key, value, ttl=60):
        self.client.setex(key, ttl, value)

    def get_cached_data(self, key):
        return …
14 0 Open
ML engineering pipelines easy

One Hot Encode Categories in Python

Convert a list of categorical strings into one-hot encoded numeric vectors using pure Python and NumPy.

one-hot encoding categorical numpy
Python
import numpy as np

categories = ["red", "green", "blue", "red", "blue", "green", "red"]

unique = sorted(set(categories))
lookup = {cat: i for i, cat in enumerate(unique)}

one_hot = []
for cat in categories:
    row = [0] * len(unique)
    row[lookup[cat]] = 1
    one_hot.append(row)

print("Categories:", categories…
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.