This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python Type Hints, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
What does name: str mean in a function signature?
Answer: Name is expected to be a string
Why: The annotation documents the expected type; it does not convert the value.
What does -> int describe?
Answer: The return type
Why: The arrow introduces the function's return annotation.
What does list[int] mean?
Answer: A list whose items are integers
Why: The type inside the brackets describes each element.
What does float | None mean?
Answer: The value may be a float or None
Why: The union lists both possible kinds of value.
Complete the parameter annotation.
def greet(name: ____) -> str:
return f"Hello, {name}"Answer: str
Why: The name should be a string.
Complete the list element type.
def total(values: list[____]) -> int:
return sum(values)Answer: int
Why: values contains integers.
Complete the union operator.
def find_price(item: str) -> float ____ None:
return NoneAnswer: |
Why: A vertical bar combines float and None.
Complete the return annotation arrow.
def double(n: int) ____ int:
return n * 2Answer: ->
Why: The arrow separates the parameter list from the return type.
What appears on the screen?
def f(n: int) -> int:
return n + 1
print(f(2))Answer: 3
Why: The hint describes the value, and the function still returns three.
What is printed?
def f(x: str = "a") -> str:
return x * 2
print(f())Answer: aa
Why: The default is a, and a repeated twice is aa.
What is the output?
def f(x: int | None) -> str:
return "none" if x is None else str(x)
print(f(None))Answer: none
Why: None takes the first branch and returns the string none.
What does this code print?
from typing import get_type_hints
def f(n: int) -> str:
return str(n)
print(get_type_hints(f)["n"].__name__)Answer: int
Why: get_type_hints reads the annotation, whose type object is named int.
Try the questions first
Open the practice page for Python Type Hints and answer the same 12 questions with instant feedback.