Reference library

Python Code Samples

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

20 matches
Functions & basics easy

Add Type Hints to Function Parameters and Return in Python

Add type hints to function parameters and return values in Python for clearer, more maintainable code using the typing module.

type-hints typing annotations
Python
from typing import List, Optional, Dict


def average(numbers: List[float]) -> float:
    return sum(numbers) / len(numbers)


def full_name(first: str, last: Optional[str] = "") -> str:
    return f"{first} {last}".strip()


def build_user(name: str, age: int, email: Optional[str] = None) -> Dict[str, object]:
    us…
15 0 Open
Functions & basics easy

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.

validation function arguments type hints
Python
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,…
12 0 Open
Errors & debugging easy

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.

result type error handling tuple unpacking
Python
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…
10 0 Open
Errors & debugging easy

How to Use Optional Return in Python Instead of Raising Exceptions

A Python function returns None for missing dictionary keys instead of raising KeyError, enabling graceful lookup handling with type hints.

optional typing dict-get
Python
from typing import Optional


def find_user(users: dict, user_id: int) -> Optional[dict]:
    """
    Look up a user by ID. Returns the user dict if found,
    otherwise returns None instead of raising KeyError.
    """
    return users.get(user_id)


def main() -> None:
    users = {
        1: {"name": "Alice", "ema…
14 0 Open
Testing & modern typing easy

Dataclass with Type Hints Fields in Python

Create a data class with typed fields and default values, then instantiate and inspect it.

dataclass type hints oop
Python
from dataclasses import dataclass


@dataclass
class Person:
    name: str
    age: int
    email: str = "unknown@example.com"
    is_active: bool = True


if __name__ == "__main__":
    person = Person(name="Alice", age=30)
    print(person)
    print(f"Name: {person.name}, Age: {person.age}, Email: {person.email}, A…
12 0 Open
Testing & modern typing easy

Design Data Helpers with Python TypedDict and Literal

Use TypedDict, Literal, and Union to define typed data shapes and parse values in Python.

typeddict literal union
Python
from typing import TypedDict, Literal, Optional, Union, List

class User(TypedDict):
    name: str
    age: int
    role: Literal["admin", "user", "guest"]

def describeUser(data: User) -> str:
    return f"{data['name']} ({data['age']}) — {data['role']}"

def parse_value(item: Union[int, str, None]) -> str:
    if it…
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 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…
13 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 Group Data by Key in Python with Type Hints

Group a list of dictionaries by a specified key using a typed helper function and print a summary of each group.

grouping type-hints dictionaries
Python
from typing import Any, Dict, List, TypeVar, Union

T = TypeVar("T")

def group_by(data: List[Dict[str, Any]], key: str) -> Dict[Any, List[Dict[str, Any]]]:
    """Group a list of dictionaries by a given key."""
    grouped: Dict[Any, List[Dict[str, Any]]] = {}
    for item in data:
        value = item.get(key)
     …
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("}"):
     …
10 0 Open
Testing & modern typing easy

How to Use Basic Type Hints (int, str) for Return Values in Python

Declare a simple function with int and str type hints and a typed return value in Python.

type-hints annotations functions
Python
def greet(name: str, age: int) -> str:
    return f"{name} is {age} years old."


if __name__ == "__main__":
    print(greet("Alice", 30))
11 0 Open
Testing & modern typing easy

How to Use Literal Type Hints in Python

Use typing.Literal to restrict a function parameter to specific allowed string values and get static type checking.

typing type-hints literal
Python
from typing import Literal

def get_status_message(status: Literal["active", "inactive", "pending"]) -> str:
    """Return a message based on the status value."""
    if status == "active":
        return "Account is active"
    elif status == "inactive":
        return "Account is inactive"
    else:
        return "…
14 0 Open
Testing & modern typing easy

How to Use Python Type Hints for Beginners

Build a data helper module with basic type hints — Union, Optional, List, Dict, Any, and TypeVar — to make your code clearer and safer.

type-hints typing annotations
Python
from typing import Any, Union, Optional, List, Dict, Tuple, Callable, TypeVar

T = TypeVar("T")

def describe(value: Any) -> str:
    """Return a human-readable description of the value's type."""
    if isinstance(value, list):
        return f"list of {len(value)} items"
    elif isinstance(value, dict):
        ret…
12 0 Open
Testing & modern typing medium

How to Use TypedDict for Data Validation in Python

Define a TypedDict schema and validate raw dictionary input with type hints for safer, more readable data handling.

typeddict typing validation
Python
from typing import Any, Dict, List, Optional, Union, TypedDict, Literal

class Product(TypedDict):
    product_id: int
    name: str
    price: Union[int, float]
    in_stock: bool
    tags: Optional[List[str]]

def validate_product(data: Dict[str, Any]) -> Product:
    product_id: int = int(data["product_id"])
    na…
13 0 Open
Testing & modern typing easy

How to Use TypedDict for Structured Dict Typing in Python

Define and use TypedDict to add type hints to dictionaries, improving code clarity and enabling static type checking in your Python projects.

typing typeddict type-hints
Python
from typing import TypedDict


class User(TypedDict):
    name: str
    age: int
    email: str


def greet(user: User) -> str:
    return f"Hello {user['name']}, age {user['age']}, contact {user['email']}"


if __name__ == "__main__":
    alice: User = {"name": "Alice", "age": 30, "email": "alice@example.com"}
    pr…
11 0 Open
Testing & modern typing easy

How to Use Union Type Hints in Python

This code demonstrates how to use Union type hints to specify that a parameter can accept multiple types (int, float, str) and handle them accordingly.

type-hints union typing
Python
from typing import Union

def process_value(value: Union[int, float, str]) -> str:
    if isinstance(value, (int, float)):
        return f"Number: {value * 2}"
    return f"String: {value.upper()}"

if __name__ == "__main__":
    print(process_value(10))
    print(process_value(3.14))
    print(process_value("hello"))
13 0 Open
Testing & modern typing medium

How to Validate Data in Python with Typing Hints

Build a runtime validation helper that checks values against Python type hints like Optional, list, and basic types.

typing validation type-hints
Python
from typing import Any, Optional, Union, TypeVar, get_origin, get_args

T = TypeVar("T")

def validate(value: Any, expected_type: type) -> Optional[str]:
    """Returns an error message if value doesn't match expected_type, else None."""
    # Handle Optional[...] types
    origin = get_origin(expected_type)
    if or…
12 0 Open
Testing & modern typing easy

How to Validate Dataclass Fields with Python Type Hints

A beginner-friendly helper that checks if instance attributes match their declared type hints using dataclasses and get_type_hints.

dataclasses type-hints validation
Python
from typing import Any, TypeVar, get_type_hints
from dataclasses import dataclass

T = TypeVar("T")

@dataclass
class User:
    name: str
    age: int
    email: str

def validate_fields(obj: Any) -> dict[str, bool]:
    """Check if object attributes match declared type hints."""
    hints = get_type_hints(obj.__class…
12 0 Open
Testing & modern typing easy

NamedTuple typed record in Python

Define a lightweight immutable record with type hints using typing.NamedTuple; access fields by name and unpack like a tuple.

namedtuple typing records
Python
from typing import NamedTuple


class Point(NamedTuple):
    x: float
    y: float
    label: str = "origin"


if __name__ == "__main__":
    p = Point(3.5, -2.0, "A")
    print(p)
    print(f"x={p.x}, y={p.y}, label={p.label}")
    print("is tuple:", isinstance(p, tuple))

    q = Point(1.0, 1.0)
    print(q)

    # …
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.