Reference library

Python Code Samples

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

13 matches
Functions & basics easy

How to Parse Function Parameters with Defaults in Python

Create Python functions with default parameter values to make arguments optional and provide sensible fallbacks.

functions default-parameters arguments
Python
def greet(name, greeting="Hello", punctuation="!"):
    """Greet a person with customizable greeting and punctuation."""
    return f"{greeting}, {name}{punctuation}"

def describe_fruit(fruit, color="unknown", ripe=False):
    """Describe a fruit with optional attributes."""
    status = "ripe" if ripe else "not ripe…
14 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
Functions & basics easy

How to Use Default Parameter Values in Python Functions

Shows how to define and call Python functions with default parameter values, including overriding some or all defaults and using keyword arguments.

functions default-parameters arguments
Python
def greet(name, greeting="Hello", punctuation="!"):
    """Return a greeting message using default parameters."""
    return f"{greeting}, {name}{punctuation}"

if __name__ == "__main__":
    # Using defaults
    print(greet("Alice"))
    
    # Overriding first default
    print(greet("Bob", "Hi"))
    
    # Overrid…
14 0 Open
Functions & basics easy

How to Use Default Parameter Values in Python Functions

This code demonstrates how to define a Python function with default parameters and call it with varying numbers of arguments to see the defaults applied.

functions parameters defaults
Python
def greet(name, greeting="Hello", punctuation="!"):
    message = f"{greeting}, {name}{punctuation}"
    print(message)

if __name__ == "__main__":
    greet("Alice")
    greet("Bob", "Hi")
    greet("Charlie", "Hey", "?")
13 0 Open
Functions & basics easy

How to use function defaults in Python

Define Python functions with default parameter values so callers can omit arguments and use sensible fallbacks.

functions default-parameters basics
Python
def greet(name="Guest", greeting="Hello", punctuation="!"):
    """Return a greeting message using default parameters."""
    return f"{greeting}, {name}{punctuation}"

def describe_pet(pet_name, animal_type="dog"):
    """Display information about a pet with a default animal type."""
    print(f"I have a {animal_type…
15 0 Open
Errors & debugging easy

How to Catch KeyError with a Default Value in Python Dictionaries

Safely retrieve dictionary values while catching KeyError and handling None values by returning a default.

keyerror dictionary error-handling
Python
def get_value(data, key, default=None):
    """
    Safely get a value from a dictionary, returning a default if the key
    is missing or the value is None.
    """
    try:
        value = data[key]
        return value if value is not None else default
    except KeyError:
        return default


if __name__ == "_…
13 0 Open
Dictionaries & sets easy

How to Use Dictionaries and Sets in Python for Beginners

Demonstrates Python dictionary operations and set operations with examples, including access, modification, defaults, and set algebra.

dictionary set beginner
Python
def demonstrate_collections():
    # Dictionary basics
    student = {
        "name": "Alice",
        "age": 20,
        "courses": ["Math", "Physics"]
    }
    print("Dictionary:", student)

    # Access and modify
    student["age"] = 21
    student["grade"] = "A"
    print("Modified:", student)

    # Get with d…
11 0 Open
OOP & classes easy

How to Build a Class Method Alternative Constructor from Dict in Python

Use a classmethod alternative constructor to build a Book instance from a dictionary with sensible defaults.

classmethod alternate-constructor oop
Python
class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages

    @classmethod
    def from_dict(cls, data):
        """Alternative constructor that builds a Book from a dictionary."""
        return cls(
            title=data["title"],
 …
15 0 Open
OOP & classes easy

How to Define Dataclass Field Defaults in Python

Implement a Python dataclass with default values for simple fields and default factories for mutable collections.

dataclasses oop defaults
Python
from dataclasses import dataclass, field
from typing import List

@dataclass
class Product:
    name: str
    price: float = 0.0
    quantity: int = 0
    tags: List[str] = field(default_factory=list)
    metadata: dict = field(default_factory=dict)

if __name__ == "__main__":
    p1 = Product("Laptop", 999.99, 5)
   …
13 0 Open
Data pipelines & processing medium

Enrich a stream with reference data by key lookup in Python

Uses streamz to join each incoming record to a reference dictionary by name, adding department and level fields or defaults.

streamz streaming join
Python
from streamz import Stream

reference = {"alice": {"dept": "eng", "level": 3}, "bob": {"dept": "sales", "level": 5}}

def enrich(record):
    name = record.get("name")
    ref = reference.get(name)
    joined = dict(record)
    if ref:
        joined.update(ref)
    else:
        joined["dept"] = "unknown"
        joi…
13 0 Open
Cloud + Python easy

How to Parse Cloud JSON Data in Python

A helper function that safely parses JSON payloads from cloud services into a clean dict with defaults and error handling.

json cloud parsing
Python
import json
from typing import Dict, Any

def parse_cloud_data(payload: str) -> Dict[str, Any]:
    """Parse a JSON payload from a cloud service into a clean dict."""
    try:
        data = json.loads(payload)
        return {
            "status": data.get("status", "unknown"),
            "region": data.get("region…
15 0 Open
System design patterns easy

Builder pattern for mocking complex objects in Python

Use a fluent Builder to construct realistic mock objects with defaults, enabling readable test data setup.

builder-pattern mock-data testing
Python
class User:
    def __init__(self):
        self.name = "default"
        self.age = 0
        self.email = "unknown@example.com"
        self.address = "unknown"

    def __repr__(self):
        return f"User(name={self.name!r}, age={self.age}, email={self.email!r}, address={self.address!r})"


class UserBuilder:
   …
15 0 Open
Production deployment patterns medium

How to Expand a Contract and Migrate Data in Python

Expand an old data contract by renaming fields and adding defaults, then migrate to a final version with deepcopy isolation.

contract migration deepcopy
Python
import json
from copy import deepcopy

# Mock data representing a user record (old contract)
old_contract = {
    "id": 1,
    "name": "Alice",
    "email": "alice@example.com",
    "age": 30,
    "status": "active"
}

# Expanded contract: adds fields with defaults and renames some fields
expand_rules = {
    "id": "u…
14 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.