Reference library

Functions & basics

Reusable building blocks — parameters, returns, scope, and clear function design.

12 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 Count Items with Default Parameters in Python

Define a Python function that prints each item with a running counter, using default parameters to allow custom start values and step increments.

functions default-parameters loops
Python
def count_items(items, start=0, step=1):
    """Count items in a list with configurable start value and step."""
    count = start
    for item in items:
        print(f"{count}: {item}")
        count += step

if __name__ == "__main__":
    fruits = ["apple", "banana", "cherry"]
    print("Default parameters (start=0…
11 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 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 Read Environment Variables in Python with Default Values

Retrieve an environment variable safely using os.getenv() with a fallback default when the variable is missing.

environment-variables os configuration
Python
import os

database_url = os.getenv("DATABASE_URL", "postgresql://localhost:5432/mydb")
print(f"Database URL: {database_url}")
10 0 Open
Functions & basics easy

How to Return Multiple Values from a Python Function

This code demonstrates how a Python function can return multiple values as a tuple, and how to unpack that tuple into individual variables.

functions tuple return-values
Python
def get_user_stats(name, score, level):
    """Return multiple values as a tuple."""
    return name, score, level

if __name__ == "__main__":
    result = get_user_stats("Alice", 95, 3)
    print(result)
    print(type(result))
    
    # Unpacking into individual variables
    player_name, player_score, player_level…
16 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 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

Browse by section

Each section groups closely related Python snippets.

Functions & basics — Python code examples

What you will find here

This page collects functions & basics snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

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.