- Sometimes you need to verify a variable's data type before doing operations on it.
- Python gives two built-in tools:
type()→ what type is this?isinstance()→ is this variable of type X?
- Returns the class/type of an object.
developer = 'Devin'
print(type(developer)) # <class 'str'>- Output
<class 'str'>→ meansdeveloperis a string.
Calling type() with no arguments → TypeError: type() takes 1 or 3 arguments.
my_integer_var = 10
print(type(my_integer_var)) # <class 'int'>
my_float_var = 4.50
print(type(my_float_var)) # <class 'float'>
my_string_var = 'hello'
print(type(my_string_var)) # <class 'str'>
my_boolean_var = True
print(type(my_boolean_var)) # <class 'bool'>
my_set_var = {7, 'hello', 8.5}
print(type(my_set_var)) # <class 'set'>
my_dictionary_var = {'name': 'Alice', 'age': 25}
print(type(my_dictionary_var)) # <class 'dict'>
my_tuple_var = (7, 'hello', 8.5)
print(type(my_tuple_var)) # <class 'tuple'>
my_range_var = range(5)
print(type(my_range_var)) # <class 'range'>
my_list = [22, 'Hello world', 3.14, True]
print(type(my_list)) # <class 'list'>
my_none_var = None
print(type(my_none_var)) # <class 'NoneType'>- Returns a boolean →
Trueif the variable matches the given type. - Syntax:
isinstance(object, type_or_tuple_of_types)
account_balance = '12'
account_balance / 2
# TypeError: unsupported operand type(s) for /: 'str' and 'int''12'is a string, not an int → division fails.
account_balance = '12'
isinstance(account_balance, int) # Falseaccount_balance = 12
isinstance(account_balance, (int, float)) # True- Returns
Trueif the variable matches any type in the tuple. - Works for
12(int) and12.0(float).
| Aspect | type() |
isinstance() |
|---|---|---|
| Returns | The class object | Boolean (True/False) |
| Use case | Inspect / debug a variable's type | Validate before using a variable |
| Multiple types? | No | Yes — pass a tuple of types |
| Common in | Debugging / learning | Production / safety checks |
account_balance = '12'
if isinstance(account_balance, (int, float)):
print(account_balance / 2)
else:
print('Not a number!')type(x)→ returns the class ofx(e.g.<class 'str'>).isinstance(x, T)→ returns True/False for whetherxis of typeT.isinstance()accepts a tuple of types for multi-type checks.- Use
isinstance()to guard operations and preventTypeErrorat runtime.
➡️
Next chapter → Python Strings — Quotes, Indexing & Immutability
Dive deeper into strings — single vs double vs triple quotes, indexing, negative indices, and Python's immutability rules.