Skip to the content

Type hints

Python · Unit 19: Clean code

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. 1. Complete the code

    Complete it to note that the function gives back a whole number.

  2. 2. Predict the output

    What does this code print?

  3. 3. Predict the output

    What does this code print?

  4. 4. Multiple choice

    You want to hint a dictionary going from name (text) to age (number). How is it written?

  5. 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. 6. Find the bug

    It should print double whatever they type. They type 5. Which line has the error?

  7. 7. Predict the output

    What does this code print?

  8. 8. Find the case that fails

    Going by its hint, last(ts) gives back the last text in the list, or None when the list is empty. Which call breaks it?

  9. 9. Multiple choice

    If Python doesn't check hints while running, what are they for?

  10. 10. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →