Type annotations describe the kinds of values code expects and returns; Python does not generally enforce them automatically at runtime.
Write readable function contracts and learn where runtime checks must establish the assumptions that annotations express.
A function signature can tell a reader what values are accepted and what may come back. Type annotations make that promise available to a checker. We will follow a possibly missing price through its caller to see what a checker can establish and what still needs runtime validation.

Format a receipt line
A canteen prints one line per item. With labels, the signature tells you how to call it without reading the body:
Read it as: takes a str called name and a float called price, returns a
str. An int like 10 is fine where a float is expected. Now the price
comes from a text box, and everything typed into a form arrives as a string:
def receipt_line(name: str, price: float) -> str:
return f"{name}: ₹{price:.2f}"
typed_in = "10"
print(receipt_line("Chai", typed_in))People expect the label to convert or reject the value. It does neither. The
fix is to convert once, where the text enters your program, so everything after
that point really gets a float:
Preparing this topic’s interactive investigation…
Look up a menu price
The menu is a dict from dish name to price, and a dish might be missing. The labels say both things:
dict[str, float] means string keys and float values. float | None is the
return label's warning: this can come back empty. Code that ignores the
warning breaks on the first missing dish:
TypeErrorOne dish is not on the menu and the whole order crashes. Skip dishes that have no price.
A checker would have pointed at total += … before you ran anything, because
the label promised None was possible. Two names you will see in older code
mean the same thing: Optional[float] is float | None, and Union[int, str] is
int | str (both from typing).
Trap:
| None(orOptional) means the value may be None. It does not mean the argument can be left out. Only a default does that:def find_price(menu, dish, fallback: float | None = None).
A check narrows what can happen next
With return type float | None, a caller starts with two possibilities.
After if price is None: return ..., the remaining branch only handles
numbers. A static checker uses this narrowing to verify later operations:
if not price would combine missing with zero; the explicit check preserves
free items. Annotating an argument as optional and making it optional to
supply are independent: the union allows a value; = None supplies a default.
An annotation never performs either a numeric conversion or a value-range
check.
Read the syntax from outside inward: list[dict[str, float]] means a list
of dictionaries, each with string keys and float values. It cannot describe
“this dict must have exactly price and quantity”; that needs named fields,
as in the next example.
Describe a train ticket
For data with a fixed set of fields you have two tools. A TypedDict
describes a plain dict key by key, which suits data that arrives as JSON. A
@dataclass turns labelled fields into a small class and writes the
constructor, the printout and == for you:
Now give each ticket a list of seats that starts empty:
ValueErrorThe class will not even build. Give every ticket its own empty list.
One-liners you'll meet
You will also see List[int] and Dict[str, int] (capitalised, imported from
typing) in code written before Python 3.9. They mean the same as
list[int] and dict[str, int].
A type describes a boundary; parsing enforces it
A TypedDict helps a checker reason about named keys, but the runtime object
is an ordinary dict. It does not validate incoming JSON. A dataclass generates
methods such as initialization and representation; its annotations also do
not reject wrong field types by themselves. Validation still belongs where
untrusted text or records enter your program.
Any permits operations a checker would otherwise question. It is useful
at an uncertain boundary, but information remains unchecked until you
validate or narrow it. Also, Python's version affects how annotations are
stored/evaluated; their non-enforcement of the declared value types is the
point this lesson relies on.
As a transfer task, annotate a lookup that can return a record or None,
then write a caller that handles both cases before reading the record.
State which malformed input a checker might flag in source and which input
can only be discovered at runtime. The exercises' execution tests verify
outputs; run a type checker separately to verify the annotations themselves.
Quick practice
def add(a: int, b: int) -> int:
return a + b
print(add("5", "5"))count: int
print(count)def greet(name: str | None) -> str:
return f"Hi {name or 'guest'}"
print(greet())TypeErrorThe function breaks its own -> int promise. Make it keep it.
🎯 Your turn
Write receipt_line(name, price) with type annotations. It returns one line
of the receipt as "name: $price", with the price to two decimals:
receipt_line("Soup", 10)→"Soup: $10.00"receipt_line("Steak", 20.5)→"Steak: $20.50"
Hint: label the signature def receipt_line(name: str, price: float) -> str:,
then return f"{name}: ${price:.2f}". The tests check the returned string, so
the labels are for readers and checkers.
Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from counting words to grouping orders by table, all typed.
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write count_words(text: str) -> int returning how many whitespace-separated words text has.
A user is {"name": str, "active": bool}. Write active_names(users) returning the names of active users only. Type it with a TypedDict.
A cart item is {"name": str, "price": float, "qty": int}. Write total_price(cart) returning the grand total (price × qty summed), rounded to 2 decimals. Type it.
An order is {"table": int, "total": float}. Write order_summary(orders) returning {"tables": <count>, "revenue": <sum of totals>, "biggest": <the order with the max total>}. Empty → counts 0 and "biggest": None.
An order is {"table": str, "dish": str}. Write group_orders(orders) returning a dict mapping each table id to its list of dishes, order preserved. Type it.