Python Function Definitions

tags #cs

Structure

def function_name(parameter: type) -> return_type:
    """
    Docstring explaining what the function does.
    
    >>> function_name(input)
    expected_output
    """
    return value

Key Components

  1. Type Hints: x: int, -> list. Helps with clarity and static analysis.
  2. Docstring: Describes purpose, parameters, and return value.
  3. Doctests: Example usage within the docstring that can be automatically tested.

Example

def is_same_length(list1: list, list2: list) -> bool:
    """
    Return True if both lists have the same length.

    >>> is_same_length([1, 2], [3, 4])
    True
    """
    return len(list1) == len(list2)