🧩 Functions, lesson 8 of 8
Type hints
Label what goes into and out of a function, and see that Python doesn't check the labels.
8 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
A type hint labels a value with the type you expect
it to have. Put name: type on a parameter, and
-> type after the parentheses for the return value.
Hints are for people and tools to read. Python stores them, but it doesn't check them when your code runs.
Hints on a function
Delete the hints and the output stays the same.
The common types are int, float, str and
bool. For collections, say what the items are:
list[int]: a list of intsdict[str, int]: a dict with string keys and int valuesX | None: a value of type X, orNone, for example "not found".
Collections and optional results
scores.get(name) returns None when the name is missing, which is exactly what int | None promises.
Hints are labels, not checks
The string "ab" goes through the same code without a complaint. Python doesn't check the hint (a type checker such as mypy would flag it before you run the code).
What does this print?
Which hint means a list where every item is an int?
Describe a person
Add type hints to describe and make age optional.
describe("Ana", 30) returns "Ana (age 30)".
When the age is left out, describe("Ben") returns
"Ben (age unknown)".
Add these hints:
nameis astrageisint | None- the function returns a
str