Python Return Values
Satellite · Functions
Python Return Values
Functions are powerful when they communicate clearly. Learn how to return structured data, multiple values, and handle the implicit None.
Basics
def total(items: list[float]) -> float:
return sum(items)
- If no
returnexecutes, the function returnsNone. - Early returns improve readability by exiting when conditions fail.
Multiple values
def min_max(values: list[int]) -> tuple[int, int]:
return min(values), max(values)
low, high = min_max(scores)
Python packs return values into tuples automatically.
Structured returns
- Use dataclasses or TypedDicts for richer payloads.
- For optional data, return
Optional[T](e.g.,-> Optional[str]).
Type hints
from typing import Optional
def find_user(id: str) -> Optional[dict]:
...
Documenting return types helps IDEs and static analyzers catch misuse.