Type Casting and Type Checking in Python

Cut the confusion. Here’s what you need to know about changing and checking variable types in Python.

What is Type Casting?

Type casting is forcing a variable to be a different data type. You take a variable of one data type and convert it to another. For example, turning the string "5" into the integer 5. Python won't guess what you mean, so you have to be explicit.

Explicit Type Casting (The kind you do yourself)

This is when you manually convert a type. You use functions like int(), float(), or str() to do the job.

  • int(variable): Tries to convert to an integer.
  • float(variable): Tries to convert to a floating-point number.
  • str(variable): Tries to convert to a string.

Example:

You get user input. It's always a string. To do math, you have to cast it.

age_string = "25"
age_integer = int(age_string)
print(age_integer + 5) # This works. "25" + 5 would have crashed.

This is essential. Without it, you get errors or weird behavior.

Implicit Type Casting (The kind Python does automatically)

Sometimes, Python converts types for you to avoid losing data. This usually happens during arithmetic operations. If you add an integer to a float, Python will upgrade the integer to a float behind the scenes to do the math.

Example:

result = 5 + 2.5 # Python treats 5 as 5.0
print(result) # Output is 7.5

You don't have to do anything here; it just works.

What is Type Checking?

Type checking is figuring out what data type a variable is. You need this to make sure your code doesn't try to do something impossible, like dividing a number by a string.

There are two main ways to do this. They are not the same.

1. isinstance() (The preferred way)

isinstance() checks if an object is an instance of a particular class or any of its subclasses. This is important for inheritance. It returns True or False.

Syntax: isinstance(variable, data_type)

Example:

x = 10
if isinstance(x, int):
    print("x is an integer")

isinstance() is flexible. For example, True is technically a subclass of int in Python, so isinstance(True, int) will return True. This can be a feature or a bug, depending on what you're doing. You can also check for multiple types at once.

isinstance(x, (int, float)) # Checks if x is an int OR a float

2. type() (The strict way)

type() tells you the exact type of an object and nothing else. It doesn't care about inheritance.

Syntax: type(variable)

Example:

x = 10
if type(x) == int:
    print("x is exactly an integer")

Using type() is less flexible. type(True) == int would be False, because the exact type of True is bool.

Use type() only when you need to be absolutely certain that a variable is of one specific type and not a subclass.

We will learn in the next lesson:

Scroll to Top