python · level 3 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Type hints say what each value should be.
A is a note about types written into the code. def total(prices: list[int]) -> int: says prices should be a list of whole numbers, and the function hands back one. Variables can have hints too: name: str = "Sam".
Write dict[str, float] for a dictionary from text to decimals, and a like str | None when a value might be missing.
Python ignores hints when it runs. A such as mypy reads them and warns you about mistakes before your code ever runs. Your editor uses them too.
def find_price(menu: dict[str, int], item: str) -> int | None:
if item in menu:
return menu[item]
return None
menu: dict[str, int] = {"tea": 180, "cake": 325}
print(find_price(menu, "cake"))
print(find_price(menu, "pie")) To check for a missing value, write if price is None:, because is asks whether it is that exact object.
guess first
The hint says int. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
def double(n: int) -> int:
return n * 2
print(double(4))
print(double("ha"))
your turn
Your turn. Add the missing hints.
Hint that scores is a list of whole numbers, and that the function returns a decimal number. The last line prints the hints Python stored.
fix it
The hint warned you, but it still crashes.
- The hint on line 1 warns that
stock_ofcan hand backNone. Which item is not in stock? - Rulers are missing, so you add
Noneto a number. Check the answer before adding it. - Store the answer in
count, then add it onlyif count is not None:, then run.
nailed it
your code says what it means now. :D
name: typeand-> typeadd hints to your code.- Python ignores hints. A type checker reads them for you.
X | Nonewarns that a value might be missing.
new words in your collection
- type hint
- union type
- type checker
This lesson isn’t saved. A free account remembers every lesson you finish.