Type Checking

Type Checking #

Occasionally, you may want to check that a variable has a certain type. You may already know from Reading 1 that you can find the type of a variable with the type function. You can technically check a type like this:

answer_to_life = 42

# This is True, but you shouldn't write it this way.
type(answer_to_life) == int

We discourage you from doing this because as we get further into this course, there are times when this will fail in unexpected ways. Instead, we recommend using the isinstance function:

answer_to_life = 42

# This is True, and is the recommended way to write this.
isinstance(answer_to_life, int)