Here’s a complete explanation of Type Error, Type Conversion, and Type Checking in Python, including definitions, examples, and best practices.
β 1. Type Error (TypeError)
πΉ Definition:
A TypeError occurs when an operation or function is applied to an object of inappropriate type.
πΉ Common Causes:
- Adding incompatible types (e.g., int + str)
- Calling a method that doesnβt exist for a data type
- Passing wrong type of argument to a function
πΉ Examples:
# Example 1: Adding int and str
a = 5
b = "hello"
print(a + b) # β TypeError: unsupported operand type(s) for +: 'int' and 'str'
# Example 2: Calling a list-specific method on an int
num = 100
num.append(50) # β TypeError: 'int' object has no attribute 'append'β 2. Type Conversion (Type Casting)
πΉ Definition:
Changing the data type of a value from one type to another is called Type Conversion or Type Casting.
πΉ Types:
- Implicit Conversion β done automatically by Python
- Explicit Conversion β done manually by the programmer using built-in functions
πΈ 2.1 Implicit Type Conversion
Python automatically converts one data type to another without user involvement, usually from lower precision to higher precision.
a = 10 # int
b = 2.5 # float
result = a + b
print(result) # 12.5 (float)
print(type(result)) # <class 'float'>πΈ 2.2 Explicit Type Conversion
You convert types manually using built-in functions like:
| Function | Converts to |
|---|---|
int(x) | Integer |
float(x) | Float |
str(x) | String |
list(x) | List |
tuple(x) | Tuple |
bool(x) | Boolean |
# String to int
num_str = "100"
num_int = int(num_str)
print(num_int + 50) # 150
# Float to int
print(int(9.87)) # 9
# Int to string
age = 25
print("Age: " + str(age)) # Age: 25β 3. Type Checking
πΉ Definition:
Verifying the data type of a variable or object.
πΉ Built-in Tools:
type()β returns the type of an objectisinstance()β checks if an object is an instance of a specific type/class
πΈ 3.1 Using type()
a = 100
print(type(a)) # <class 'int'>
b = [1, 2, 3]
print(type(b)) # <class 'list'>β οΈ Note: type() returns the exact type, and is not suitable for checking inheritance.
πΈ 3.2 Using isinstance()
Preferred over type() for type checking.
x = 10
print(isinstance(x, int)) # True
print(isinstance(x, float)) # False
y = [1, 2, 3]
print(isinstance(y, list)) # True
print(isinstance(y, object)) # True (because all in Python are objects)πΈ Best Practice for Type Checking:
def greet(name):
if not isinstance(name, str):
raise TypeError("name must be a string")
print("Hello, " + name)
greet("Himanshu") # β
greet(123) # β TypeErrorSummary Table
| Concept | Purpose | Method/Function | Example |
|---|---|---|---|
| Type Error | Wrong operation on incompatible types | – | 5 + "abc" |
| Type Conversion | Change type from one to another | int(), float(), str() | str(25) β "25" |
| Type Checking | Check object type | type(), isinstance() | isinstance(10, int) β True |
