Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

94 matches
Functions & basics easy

How to Write a Python Decorator with functools.wraps

Create a decorator that wraps a function while preserving its metadata using functools.wraps.

decorator functools wraps
Python
from functools import wraps


def logger(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper


@logger
def greet(name):
    """Return a friendly greeting."""
    return f"Hello, {name}!"


if __name__ == "__main__":…
12 0 Open
Functions & basics easy

How to measure function memory with sys.getsizeof in Python

Measure the memory footprint of Python functions (user-defined and built-in) using sys.getsizeof.

sys getsizeof memory
Python
import sys

def sample_function(a, b, c):
    return a + b - c

def measure_function_memory(func):
    size = sys.getsizeof(func)
    print(f"Memory size of {func.__name__}: {size} bytes")

if __name__ == "__main__":
    measure_function_memory(sample_function)
    measure_function_memory(print)
    measure_function_m…
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

Mutual Recursion for Even/Odd Check in Python

Implements even and odd checks using two functions that call each other recursively, demonstrating base cases and alternating calls.

recursion functions mutual-recursion
Python
def is_even(n):
    if n == 0:
        return True
    return is_odd(n - 1)

def is_odd(n):
    if n == 0:
        return False
    return is_even(n - 1)

if __name__ == "__main__":
    for num in range(0, 11):
        print(f"{num}: even={is_even(num)}, odd={is_odd(num)}")
12 0 Open
Functions & basics easy

Profile Python functions with cProfile

Profile a Python program with cProfile, capture the stats in memory, and print a sorted performance report.

cprofile performance profiling
Python
import cProfile
import pstats
import io


def slow_function():
    total = 0
    for i in range(100000):
        total += i ** 2
    return total


def medium_function():
    return sum(range(10000))


def fast_function():
    return sum(range(100))


def main():
    result1 = slow_function()
    result2 = medium_func…
11 0 Open
Functions & basics easy

Python Filter Function with Default Parameters for Beginners

Create a reusable filter function with default parameters to keep or exclude numbers above or below a threshold.

functions default-parameters filter
Python
def filter_numbers(numbers, threshold=0, reverse=False):
    """Return numbers that pass the threshold filter.

    Args:
        numbers: list of numbers to filter
        threshold: minimum value to keep (default 0)
        reverse: if True, keep numbers below threshold (default False)
    """
    if reverse:
      …
13 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
Functions & basics easy

Write a Pure Function Without Side Effects in Python

Defines a pure function that adds one to a number without modifying external state.

pure functions side effects functions
Python
def add_one(x: int) -> int:
    """Adds 1 to the input without modifying any external state."""
    return x + 1

if __name__ == "__main__":
    original = 5
    result = add_one(original)
    print(f"Original: {original}")
    print(f"Result: {result}")
    print(f"Original unchanged: {original}")
12 0 Open
Functions & basics easy

Write a Recursive Factorial Function in Python

Define a recursive factorial function that handles edge cases and returns the product of all positive integers up to n.

recursion factorial functions
Python
def factorial(n):
    """Return the factorial of n using recursion."""
    if n < 0:
        raise ValueError("Factorial is not defined for negative numbers")
    if n == 0 or n == 1:
        return 1
    return n * factorial(n - 1)

if __name__ == "__main__":
    print(factorial(5))
14 0 Open
Functions & basics easy

Compound interest calculator in Python

Compute future investment value with the compound interest formula and a readable year-by-year loop.

math finance functions
Python
def future_value(
    principal: float,
    annual_rate: float,
    years: int,
    compounds_per_year: int = 12,
) -> float:
    """Return balance after compound interest (rounded to cents)."""
    rate_per_period = annual_rate / compounds_per_year
    periods = compounds_per_year * years
    amount = principal * (1 …
54 0 Open
Errors & debugging easy

How to Handle ValueError and Multiple Exceptions in Python

This code demonstrates try/except blocks for beginners, handling ZeroDivisionError, TypeError, and ValueError with two practical functions: dividing numbers and parsing strings to floats.

try-except valueerror exception-handling
Python
def divide_numbers(a, b):
    """Divide two numbers with error handling for beginners."""
    try:
        result = a / b
        print(f"{a} / {b} = {result}")
        return result
    except ZeroDivisionError:
        print(f"Error: Cannot divide {a} by zero!")
    except TypeError:
        print(f"Error: Both argu…
13 0 Open
Files & data easy

File Data Helper Functions in Python

Read and write text and JSON files, and list files in a directory, using pathlib-based helper functions.

file-io pathlib json
Python
from pathlib import Path

def load_text_file(filepath):
    """Read a text file and return its contents as a string."""
    path = Path(filepath)
    if not path.exists():
        raise FileNotFoundError(f"File not found: {filepath}")
    return path.read_text(encoding="utf-8")

def save_text_file(filepath, content):
…
15 0 Open
Files & data easy

How to Parse JSON, TXT, and CSV Files in Python

This code provides simple functions to read and parse JSON, text, and CSV files using Python's standard library, returning native data structures.

json csv file parsing
Python
import json
from pathlib import Path

def parse_json_file(filepath):
    """Read and parse a JSON file, returning its contents."""
    path = Path(filepath)
    with path.open('r', encoding='utf-8') as f:
        return json.load(f)

def parse_txt_lines(filepath):
    """Read a text file and return non-empty stripped …
15 0 Open
Files & data easy

How to Read and Write Text Files in Python

This code provides simple helper functions to save and load text files using Python's standard pathlib library.

file-io pathlib text-files
Python
from pathlib import Path


def save_text_data(filename: str, content: str) -> None:
    file_path = Path(filename)
    file_path.write_text(content, encoding="utf-8")


def load_text_data(filename: str) -> str:
    file_path = Path(filename)
    return file_path.read_text(encoding="utf-8")


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

Convert Lists and Dictionaries to Sets in Python

Convert lists of pairs into dictionaries and lists or dictionaries into sets using simple helper functions.

dict set conversion
Python
def convert_to_dict(data):
    """Convert list of tuples or lists into a dictionary."""
    return dict(data)


def convert_to_set(data):
    """Convert list or dictionary into a set of its keys/values."""
    if isinstance(data, dict):
        return set(data.keys())
    return set(data)


def convert_collection(data…
14 0 Open
OOP & classes easy

How to Create Static Methods in a Python Class

Shows how to define and call static methods inside a class using @staticmethod, with utility functions that don't need instance or class state.

static-method oop class
Python
class MathUtils:
    """Utility class demonstrating static methods."""
    
    @staticmethod
    def add(a, b):
        """Return the sum of two numbers."""
        return a + b
    
    @staticmethod
    def multiply(a, b):
        """Return the product of two numbers."""
        return a * b
    
    @staticmethod
…
14 0 Open
OOP & classes easy

How to Implement the Decorator Pattern in Python to Add Behavior

This Python code demonstrates the decorator pattern by wrapping a function to add logging behavior without modifying the original function.

decorator pattern logging
Python
import functools

def logger(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with {args} {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@logger
def add(a, b):
   …
11 0 Open
Comprehensions & generators easy

How to Use Comprehensions and Generators in Python

Demonstrate list, set, and dictionary comprehensions plus generator expressions and generator functions in one beginner-friendly script.

comprehensions generators yield
Python
def demonstrate_comprehensions_generators():
    # List comprehension: transform and filter in one line
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    squares = [num ** 2 for num in numbers if num % 2 == 0]
    print(f"Square of even numbers (list comprehension): {squares}")

    # Set comprehension: unique values
…
15 0 Open
Comprehensions & generators easy

Python Comprehensions and Generators for Beginners

Learn list, dict, and set comprehensions plus generator expressions and generator functions with clear, runnable examples.

comprehensions generators lazy-evaluation
Python
# Demonstrates list comprehensions, dict comprehensions, set comprehensions, and generators

def demonstrate_comprehensions():
    # List comprehension: squares of even numbers
    numbers = range(1, 11)
    even_squares = [n ** 2 for n in numbers if n % 2 == 0]
    
    # Dict comprehension: number to its factorial
 …
15 0 Open
Comprehensions & generators easy

Write Data Helpers with Comprehensions and Generators in Python

Demonstrates list, dict, and set comprehensions plus generator expressions and generator functions for building concise data helpers.

comprehensions generators data-helpers
Python
# Basic comprehensions and generators demo

# List comprehension: squares of evens
squares = [x * x for x in range(10) if x % 2 == 0]
print("List comp:", squares)

# Dictionary comprehension: char -> count
text = "hello"
char_counts = {c: text.count(c) for c in set(text)}
print("Dict comp:", char_counts)

# Set compre…
10 0 Open
AI & LLM integration patterns easy

How to Build an Entity Memory Dict to Store Facts in Python

Store and recall facts about entities using nested dictionaries with remember, recall, and forget functions in Python.

memory dict nested-dict
Python
facts = {}

def remember(entity, attribute, value):
    if entity not in facts:
        facts[entity] = {}
    facts[entity][attribute] = value

def recall(entity, attribute):
    return facts.get(entity, {}).get(attribute, None)

def forget(entity, attribute=None):
    if attribute is None:
        facts.pop(entity, …
12 0 Open
Data pipelines & processing easy

Create Data Helper Functions in Python for Beginners

Build reusable Python helper functions to load, filter, sort, summarize, and save JSON data — a beginner-friendly starting point for small data pipelines.

json pipeline helpers
Python
import json
from pathlib import Path
from typing import Any, Dict, List


def load_json_file(filepath: str) -> Dict[str, Any]:
    """Load JSON data from a file."""
    with Path(filepath).open("r", encoding="utf-8") as file:
        return json.load(file)


def filter_by_key(
    data: List[Dict[str, Any]], key: str,…
14 0 Open
Data pipelines & processing easy

How to Build Data Processing Functions in Python

Create reusable helper functions to load, filter, transform, and aggregate CSV data in Python.

csv pipeline etl
Python
import csv
from pathlib import Path


def load_data(filepath):
    """Load CSV data into a list of dicts."""
    with open(filepath, "r", newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def filter_rows(rows, column, value):
    """Keep rows where column equals value."""
    return [row for…
11 0 Open
Data pipelines & processing easy

Pipeline stage compose functions left to right in Python

Compose multiple functions into a left-to-right pipeline so each stage receives the output of the previous one.

composition pipeline functional
Python
def compose(*funcs):
    """Compose functions left to right: compose(f, g, h)(x) == h(g(f(x)))"""
    def composed(arg):
        result = arg
        for func in funcs:
            result = func(result)
        return result
    return composed

if __name__ == "__main__":
    def add_one(x):
        return x + 1

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