Type Hints & Typing
Python lets you annotate what types your functions expect and return. These type hints do not change how the code runs (Python does not enforce them at runtime), but they are read by your editor, by type checkers like mypy, and by libraries: the entire AI-tooling layer later in this course (JSON schemas, function/tool calling, Pydantic-style validation) is built on them. Treat them as machine-checked documentation.
The shape is name: type for parameters and -> type for the return:
def area(width: float, height: float) -> float:
return width * heightFor containers, use the built-in generics (Python 3.9+):
tags: list[str] # a list of strings
scores: dict[str, int] # str keys, int values
point: tuple[int, int] # a pair of intsWhen a value can be missing, say so with X | None (Python 3.10+; on older versions write Optional[X] from typing):
def first(items: list[str]) -> str | None:
return items[0] if items else NoneDefaults combine with hints as you would expect: def f(n: int = 0) -> int:. And because the hints are real objects, your program (and the grader) can read them back via func.__annotations__, a dict from each parameter name (plus 'return') to its annotated type. That is exactly how tool-calling frameworks autogenerate a schema from a function signature.
Write two fully type-hinted functions. (1) first_or_none(items: list[str]) -> str | None returns the first item, or None for an empty list. (2) lookup(scores: dict[str, int], name: str, default: int = 0) -> int returns scores[name] if present, else default. Annotate every parameter and the return type exactly as shown (the grader reads __annotations__).
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.