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
- Type Hints:
x: int,-> list. Helps with clarity and static analysis. - Docstring: Describes purpose, parameters, and return value.
- 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)