Checking Types

Data Types

Checking Types

In this tutorial, we'll use type() and isinstance() to inspect values.

Sometimes you need to know what type a value is. Python gives you tools for that.

Using type()

type() tells you the type of a value:

name = "Ada"
age = 12
price = 4.99
is_member = True

print(type(name))
print(type(age))
print(type(price))
print(type(is_member))

Output:

<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

The names mean:

  • str: string
  • int: integer
  • float: decimal number
  • bool: boolean

Using isinstance()

isinstance() checks whether a value has a type:

score = 10

print(isinstance(score, int))
print(isinstance(score, str))

Output:

True
False

This is useful when your code needs to behave differently depending on the value.

Debugging With Types

If a calculation behaves strangely, check the types:

number = "10"

print(type(number))
print(number + number)

Output:

<class 'str'>
1010

Now you know number is text, not an integer.

Do Not Overuse Type Checks

You do not need to check every value in normal code. Use type checks when:

  • You are debugging
  • You are learning what Python is doing
  • Your program accepts values from outside, such as user input

Practice

Create four variables: a name, an age, a price, and a logged-in flag. Print each value and its type.