Chapters
Python114 chapters

Exercises

Type Hints

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Annotate greet so it takes a str and returns a str.

Python
def greet(name):
    return f"Hello, {name}"

print(greet("Ada"))
print(greet.__annotations__)
Exercise 2

find may return an index or nothing. Annotate it correctly.

Python
def find(names, target):
    for index, name in enumerate(names):
        if name == target:
            return index
    return None

print(find(["ada"], "ada"), find(["ada"], "alan"))
Exercise 3

The default is None, so the hint is a contradiction. Fix the annotation.

Python
def add(item: str, target: list[str] = None) -> list[str]:
    if target is None:
        target = []
    target.append(item)
    return target

print(add("a"))