Skip to content

Latest commit

 

History

History
130 lines (88 loc) · 3.32 KB

File metadata and controls

130 lines (88 loc) · 3.32 KB

Python type() & isinstance() — Checking Variable Types

🧠 Why Check Types?

  • 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?

🔍 The type() Function

  • Returns the class/type of an object.
developer = 'Devin'
print(type(developer))  # <class 'str'>
  • Output <class 'str'> → means developer is a string.
⚠️

Calling type() with no argumentsTypeError: type() takes 1 or 3 arguments.

type() Output for Each Data Type

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'>

✅ The isinstance() Function

  • Returns a booleanTrue if the variable matches the given type.
  • Syntax: isinstance(object, type_or_tuple_of_types)

Why You Need It — Type Mismatch Example

account_balance = '12'
account_balance / 2
# TypeError: unsupported operand type(s) for /: 'str' and 'int'
  • '12' is a string, not an int → division fails.

Single Type Check

account_balance = '12'
isinstance(account_balance, int)  # False

Multiple Type Check (use a tuple)

account_balance = 12
isinstance(account_balance, (int, float))  # True
  • Returns True if the variable matches any type in the tuple.
  • Works for 12 (int) and 12.0 (float).

🆚 type() vs isinstance()

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

💡 Common Pattern — Safe Operations

account_balance = '12'

if isinstance(account_balance, (int, float)):
    print(account_balance / 2)
else:
    print('Not a number!')

✅ Key Takeaways

  • type(x) → returns the class of x (e.g. <class 'str'>).
  • isinstance(x, T) → returns True/False for whether x is of type T.
  • isinstance() accepts a tuple of types for multi-type checks.
  • Use isinstance() to guard operations and prevent TypeError at 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.