Reference library

Python Code Samples

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

6 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 medium

How to Parse Function Signatures in Python with inspect

Extract a function's parameter names, kinds, defaults, annotations, and return type using Python's built-in inspect module.

inspect function signature introspection
Python
import inspect

def example_function(a: int, b: str = "default", *args, c: float = 1.5, **kwargs) -> bool:
    """An example function with various parameter types."""
    return True

def parse_signature(func):
    """Parse a function's signature using the inspect module."""
    sig = inspect.signature(func)
    param…
13 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 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))
12 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…
13 0 Open
Database scaling & optimization easy

How to Count Star vs Estimate Matches in Python

Count how many times 'star' and 'estimate' annotations match their actual labels in a list of mock comparison results.

counting dictionary matching
Python
def count_star_vs_estimate(mock_scores):
    """
    Count the number of times 'star' wins and 'estimate' wins
    from a list of mock comparison results.

    Args:
        mock_scores: list of tuples, each (annotation, actual)
                     where annotation is 'star' or 'estimate'

    Returns:
        dict w…
12 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.