Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 05 / Topic 5 of 9

Docstrings and type hints

A docstring is a string right under def. It explains what the function does. help() shows it. Type hints say what types you expect: rupees: float means "a float comes in", -> int means "an int comes out". Python does not enforce them, but they help readers and editors. You will also see list[int] (a list of ints), tuple[int, float] (a tuple with an int, then a float) and str | None (a str or None).

Real-world example: a function to convert rupees to paise.

def to_paise(rupees: float) -> int:
    """Convert an amount in rupees to paise (1 rupee = 100 paise)."""
    return round(rupees * 100)

print(to_paise(12.5))            # 1250
print(to_paise.__doc__)          # Convert an amount in rupees to paise (1 rupee = 100 paise).

๐Ÿ” Going deeper: hints are saved in to_paise.__annotations__ and are ignored when the code runs: to_paise("12") still runs and fails inside the function. Tools such as mypy read the hints and warn you before you run the code.

Done here? The practice set for Part 5 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide