Reference library

Python Code Samples

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

34 matches
Functions & basics easy

Call a Function Dynamically by Name in Python

Use globals() to look up and call a function by its name as a string, with optional arguments.

globals dynamic-dispatch reflection
Python
def greet():
    return "Hello from greet!"

def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

if __name__ == "__main__":
    func_name = "add"
    args = (3, 5)
    
    # Call function dynamically by name from globals
    result = globals()[func_name](*args)
    print(f"{func_name}({', '.join(ma…
13 0 Open
Functions & basics easy

How to Build Partial Functions with functools.partial in Python

Create reusable partial functions that pre-fill arguments using functools.partial, like making square and cube functions from a general power function.

functools partial higher-order-functions
Python
```python
from functools import partial

def power(base, exponent):
    """Calculate base raised to the exponent power."""
    return base ** exponent

# Create partial functions for common powers
square = partial(power, exponent=2)
cube = partial(power, exponent=3)

if __name__ == "__main__":
    squares = [square(x)…
12 0 Open
Functions & basics easy

How to Build a Simple Decorator That Logs Function Calls in Python

This code shows how to create a reusable decorator that logs each function call, including arguments, return value, and execution time.

decorator logging functools
Python
import functools
import time

def log_calls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} return…
11 0 Open
Functions & basics easy

How to Create Functions with Default Parameters in Python

This code defines two Python functions using default parameters to handle missing arguments gracefully, demonstrating how to work with optional inputs and keyword arguments.

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


def create_profile(username="anonymous", age=0, city="Unknown", active=True):
    """Create a user profile dictionary with default values."""
    r…
14 0 Open
Functions & basics easy

How to Define a Function with Default Parameter Values in Python

This code demonstrates defining a Python function with default parameter values, showing how to call it with zero, one, or two arguments.

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


if __name__ == "__main__":
    # Call with no arguments – uses both defaults
    print(greet())

    # Call with one argume…
13 0 Open
Functions & basics easy

How to Document Python Functions with Google Style Docstrings

Document a Python function with a Google style docstring to describe arguments and return values clearly.

docstrings documentation functions
Python
def calculate_rectangle_area(length: float, width: float) -> float:
    """Calculate the area of a rectangle.

    Args:
        length (float): The length of the rectangle in meters.
        width (float): The width of the rectangle in meters.

    Returns:
        float: The area of the rectangle in square meters.
 …
13 0 Open
Functions & basics medium

How to Invalidate Cache When Arguments Change in Python

A memoization decorator that caches function results keyed by arguments, automatically invalidating when inputs change.

decorators caching memoization
Python
from functools import wraps

def memoize(func):
    cache = {}
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        key = (args, tuple(sorted(kwargs.items())))
        if key not in cache:
            cache[key] = func(*args, **kwargs)
        return cache[key]
    
    return wrapper

@memoize
def expensiv…
14 0 Open
Functions & basics easy

How to Parse Command Line Arguments in Python with argparse

Build a CLI that accepts positional integers, an optional --sum flag, and a --verbose switch, all with Python's standard argparse library.

argparse cli command line
Python
import argparse

def main():
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('numbers', metavar='N', type=int, nargs='+',
                        help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
         …
11 0 Open
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 easy

How to Use *args and **kwargs in Python Functions

Implement a variadic function that accepts arbitrary positional and keyword arguments using *args and **kwargs.

args kwargs variadic
Python
def display_info(title, *args, **kwargs):
    """Display positional and keyword arguments received."""
    print(f"Title: {title}")
    print(f"Additional positional args ({len(args)}):")
    for i, arg in enumerate(args, 1):
        print(f"  {i}. {arg}")
    print(f"Keyword args ({len(kwargs)}):")
    for key, value…
14 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 Default Parameters in Python Functions

Define a Python function with default parameters and call it using positional and keyword arguments.

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

if __name__ == "__main__":
    print(greet("Alice"))                 # Uses both defaults
    print(greet("Bob", "Hi"))             # Uses default punctua…
13 0 Open
Functions & basics easy

How to Use Default Parameters with Python's Split Function

Create a reusable Python wrapper around str.split with sensible default parameters for delimiter and maxsplit, showing beginners how default arguments work.

strings default-parameters functions
Python
def split_with_defaults(text, delimiter=" ", maxsplit=-1):
    """
    Split a string into parts using a delimiter.
    Default behavior: split on spaces, unlimited splits.
    """
    parts = text.split(delimiter, maxsplit)
    return parts


if __name__ == "__main__":
    # Example usage with defaults and custom par…
14 0 Open
Functions & basics easy

How to Use Keyword-Only Arguments in Python Functions

Define Python functions with keyword-only arguments using the * separator to enforce clarity and prevent positional misuse.

functions keyword-arguments function-signature
Python
def greet(name, *, greeting="Hello", punctuation="!"):
    """Greet someone with a customizable message using keyword-only arguments."""
    message = f"{greeting}, {name}{punctuation}"
    return message

if __name__ == "__main__":
    # Basic call with only the positional argument
    print(greet("Alice"))

    # Al…
15 0 Open
Functions & basics easy

How to Use Lambda Sorting Keys in Python

Learn to sort lists of dictionaries using lambda functions as key arguments in Python's sorted() method.

lambda sorting beginner
Python
# Demonstrate lambda as a sorting key function

students = [
    {"name": "Alice", "grade": 88},
    {"name": "Bob", "grade": 92},
    {"name": "Charlie", "grade": 75},
    {"name": "Diana", "grade": 95}
]

# Sort by grade (ascending) using a lambda key
sorted_by_grade = sorted(students, key=lambda student: student["g…
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,…
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
Functions & basics easy

Python Function Default Parameters Explained with Examples

Learn how to define Python functions with default parameter values and call them with fewer arguments than declared.

functions default-parameters args
Python
def greet(name, greeting="Hello", punctuation="!"):
    return f"{greeting}, {name}{punctuation}"

def calculate_area(length, width=1, unit="sq units"):
    area = length * width
    return f"Area: {area} {unit}"

if __name__ == "__main__":
    print(greet("Alice"))
    print(greet("Bob", "Hi"))
    print(greet("Charl…
14 0 Open
Comprehensions & generators easy

How to Use starmap() to Unpack Tuple Arguments in Python

Use itertools.starmap to apply a function to each tuple in an iterable, unpacking tuple elements as separate arguments and returning an iterator of results.

itertools starmap generators
Python
from itertools import starmap

def multiply(a, b):
    return a * b

if __name__ == "__main__":
    pairs = [(2, 3), (4, 5), (6, 7), (8, 9)]
    results = list(starmap(multiply, pairs))
    print(results)
14 0 Open
Automation & scripting easy

How to Build a Python argparse CLI for Beginners

Build a beginner-friendly command-line interface using Python's argparse module with positional and optional arguments.

argparse cli command-line
Python
import argparse

def greet(name, greeting="Hello", uppercase=False):
    message = f"{greeting}, {name}!"
    if uppercase:
        message = message.upper()
    return message

def main():
    parser = argparse.ArgumentParser(description="A simple CLI greet tool for beginners.")
    parser.add_argument("name", help="…
15 0 Open
Automation & scripting easy

How to Create a Simple Python CLI with argparse

Build a beginner-friendly command-line tool with argparse that accepts positional and optional arguments to greet users flexibly.

argparse cli command-line
Python
import argparse

def greet(name, greeting="Hello", uppercase=False):
    message = f"{greeting}, {name}!"
    return message.upper() if uppercase else message

def main():
    parser = argparse.ArgumentParser(
        description="A simple CLI tool that greets users."
    )
    parser.add_argument(
        "name",
   …
15 0 Open
Automation & scripting easy

How to Implement argparse CLI Command in Python

Build a beginner-friendly command-line tool with argparse that accepts positional and optional arguments, flags, and prints a customizable greeting.

argparse cli command-line
Python
import argparse


def main():
    parser = argparse.ArgumentParser(description="A simple CLI tool to greet users.")
    parser.add_argument("name", help="Your name")
    parser.add_argument("-g", "--greeting", default="Hello", help="Greeting word (default: Hello)")
    parser.add_argument("--uppercase", action="store_…
15 0 Open
Automation & scripting easy

How to Parse CLI Arguments in Python with argparse

Build a beginner-friendly CLI with argparse that accepts optional --name, --greeting, and --uppercase flags, then prints a customizable greeting.

argparse cli command-line
Python
import argparse

def main():
    parser = argparse.ArgumentParser(description="Greet a user with optional customization.")
    parser.add_argument("--name", default="world", help="Name to greet")
    parser.add_argument("--greeting", default="Hello", help="Greeting word")
    parser.add_argument("--uppercase", action=…
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.