HomePYTHONType Error, Type Conversion, and Type Checking in Python

Type Error, Type Conversion, and Type Checking in Python

Type Error, Type Conversion, and Type Checking

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:

  1. Implicit Conversion – done automatically by Python
  2. 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:

FunctionConverts 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 object
  • isinstance() – 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)          # ❌ TypeError

Summary Table

ConceptPurposeMethod/FunctionExample
Type ErrorWrong operation on incompatible types5 + "abc"
Type ConversionChange type from one to anotherint(), float(), str()str(25) β†’ "25"
Type CheckingCheck object typetype(), isinstance()isinstance(10, int) β†’ True

Share:Β 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *