Important Notice:

TypeError

TypeError

25 views 2 min read

TypeError (टाइप एरर) :-

TypeError तब आती है जब किसी Operation (कार्य) या Function में गलत Data Type (डेटा प्रकार) का उपयोग किया जाता है। अर्थात, जब दो ऐसे Data Types पर Operation किया जाता है जो एक-दूसरे के साथ Compatible (संगत) नहीं होते।

English:

A TypeError occurs when an operation or function is performed on an incompatible data type. In other words, Python raises a TypeError when two data types cannot be used together in the given operation.

 

Wrong Example 1: Adding Integer and String

 a = 10
b = "20"

print(a + b)
 

Output:

TypeError: unsupported operand type(s) for +: 'int' and 'str'
 

Correct Example -

a = 10
b = int("20")

print(a + b)

Output:

30
 

Wrong Example 2: Adding Number and String

 
 
age = 18

print("Age: " + age)

Output:

TypeError: can only concatenate str (not "int") to str
 

Correct Example -

age = 18
print("Age: " + str(age))

Output:

Age: 18
 

Wrong Example 3: Wrong Number of Arguments

 
def add(a, b):
    return a + b

print(add(10))
 

Output:

TypeError: add() missing 1 required positional argument: 'b'
 

Correct Example

 def add(a, b):
    return a + b

print(add(10, 20))
 

Output:

30
 

Wrong Example 4: Invalid Operation on Data Type

text = "Python"

print(text - "Py")
 
 

Output:

TypeError: unsupported operand type(s) for -: 'str' and 'str'
 

Correct Example

 
text = "Python"

print(text.replace("Py", ""))
 

Output:

thon

Related Notes