Type hints
Python · Unit 19: Clean code
- Full plan
- Python
- 10 exercises
You have written type hints already: back in unit 14, inside a @dataclass, you wrote price: int.
The same fits in any function. Parameters take : type, and what comes out goes after the arrow ->.
def repeat(t: str, n: int) -> str:
return t * n
print(repeat("ab", 3))Prints
ababab
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Complete the code
Complete it to note that the function gives back a whole number.
2. Predict the output
What does this code print?
3. Predict the output
What does this code print?
4. Multiple choice
You want to hint a dictionary going from name (text) to age (number). How is it written?
5. Put the lines in order
Put the function in order. It gives back the average, and 0.0 when the list is empty.
6. Find the bug
It should print double whatever they type. They type 5. Which line has the error?
7. Predict the output
What does this code print?
8. Find the case that fails
Going by its hint,
last(ts)gives back the last text in the list, orNonewhen the list is empty. Which call breaks it?9. Multiple choice
If Python doesn't check hints while running, what are they for?
10. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.