Type hints
Describe the values a function accepts and returns.
A type hint describes the expected type of a value. In def total(values: list[int]) -> int:, the argument is a list of integers and the result is an integer. A union such as str | None means either type is possible.
Python normally does not enforce these hints at runtime. A static type checker can flag problems before you run the code. Validate values read from files or other outside sources when correctness depends on their types.
The annotation documents that every item should be a whole number.
Try it yourself
Write first_or_none(names) with an input hint of list[str] and a return hint of str | None. Print the result for ["Ada", "Grace"] and for an empty list.
Target output
Ada
NoneShow a hint
Use return names[0] if names else None.
Ready
Run your code to see the output here.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
def first_or_none(names: list[str]) -> str | None:
return names[0] if names else None
print(first_or_none(["Ada", "Grace"]))
print(first_or_none([]))