Exercises
Type Hints
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
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__)A colon for the parameter, an arrow for the return.
def greet(name: str) -> str:
return f"Hello, {name}"
print(greet("Ada"))
print(greet.__annotations__)Exercise 2Passed
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"))list[str] for the names, and int | None for the return.
def find(names: list[str], target: str) -> int | None:
for index, name in enumerate(names):
if name == target:
return index
return None
print(find(["ada"], "ada"), find(["ada"], "alan"))Exercise 3Passed
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"))Say the parameter may be missing.
def add(item: str, target: list[str] | None = None) -> list[str]:
if target is None:
target = []
target.append(item)
return target
print(add("a"))