Practice: Type Hints

« Read the chapter

Q1. Hint a function

BeginnerCoding

Write a function add(a, b) with int hints for both parameters and the return value, then print add(2, 3).

Goal: Annotate a function

Q2. List of strings

BeginnerCoding

Write shout(words) that takes list[str] and returns a list of uppercase words. Print shout(['hi', 'yo']).

Goal: Hint collections

Q3. Optional lookup

IntermediateCoding

Write get_price(prices, item) hinted as dict[str, float] and str returning float | None. Print the result for 'tea' in {'tea': 2.5} and for 'milk'.

Goal: Optional values

Q4. Tuple return

IntermediateCoding

Write min_max(nums: list[int]) returning tuple[int, int]. Print min_max([4, 9, 1, 7]).

Goal: Tuple hints

Q5. Show the annotations

IntermediateCoding

Define def f(x: int, y: str = 'a') -> bool and print f.__annotations__ (return True from the body).

Goal: Inspect annotations

Q6. Generic last item

AdvancedCoding

Write a generic last(items: list[T]) -> T using TypeVar and print last([1, 2, 3]) and last(['x', 'y']).

Goal: Generics

Q7. Type alias

IntermediateCoding

Create an alias Pair = tuple[int, int] and a function swap(p: Pair) -> Pair. Print swap((1, 2)).

Goal: Type aliases

Q8. Wrong type allowed

BeginnerOutput

What does this print?

Code
def twice(n: int) -> int:
    return n * 2

print(twice('ha'))

Goal: Hints are not enforced

Q9. Annotations dict

IntermediateOutput

What does this print?

Code
def g(a: str) -> None:
    pass

print(g.__annotations__)

Goal: Read __annotations__

Q10. Variable without value

IntermediateOutput

What does this print?

Code
x: int
print('start')
try:
    print(x)
except NameError:
    print('no value')

Goal: Variable annotations

Q11. Union result

BeginnerOutput

What does this print?

Code
def show(v: int | str) -> str:
    return str(v) + '!'

print(show(7))
print(show('go'))

Goal: Union types

Q12. Module annotations

AdvancedOutput

What does this print?

Code
count: int = 5
name: str = 'Lee'
print(__annotations__)

Goal: Variable annotations

Q13. Fix the Optional use

IntermediateDebugging

This code crashes when the key is missing. Fix it so it prints 0 for a missing name.

Code
def length(d: dict[str, str], k: str) -> int:
    return len(d.get(k))

print(length({'a': 'xyz'}, 'b'))

Goal: Handle Optional

Q14. Fix the list hint

IntermediateDebugging

This code fails with a TypeError when defining the function. Fix the hint so it prints 6.

Code
def total(nums: list(int)) -> int:
    return sum(nums)

print(total([1, 2, 3]))

Goal: Fix generic syntax

Q15. Hints at run time

BeginnerConceptual

Does Python raise an error if you call a function hinted with int using a string? Explain.

Goal: Enforcement of hints

Q16. Why TypeVar

AdvancedConceptual

Why is def first(items: list[T]) -> T better than def first(items: list) -> Any?

Goal: Understand generics

Q17. Document an API

IntermediateApplication

You write a function that reads a user dictionary and returns the email or None. Write a hinted version and print the result for {'email': 'a@b.com'}.

Goal: Use hints to document