Python TypeError: ‘int’ object is not subscriptable
This error occurs when you try to use the integer type value as an array.
In simple terms, this error occurs when your program has a variable that is treated as an array by your function, but actually, that variable is an integer.
Example 1) Error Code
#Simple program with error productPrice = 3000 print(productPrice)
Traceback (most recent call last): File "F:/python code/intProgram.py", line 3, in <module> print(productPrice) TypeError: 'int' object is not subscriptable
In the above program as you can see we have declared an integer variable ‘productPrice’ and in the next line, we are trying to print the value of integer variable productPrice as a list.
productPrice = 3000 print("Product price is ", productPrice)
Example 2: Error Code
#Code with error #User input start productName = input("Enter product name : ") productPrice = input("Enter product price : ") #User input ends x = 0 #giving the value of product price to the variable x in int format int(x[productPrice]) #calculating the price after discount productPriceAfterDiscount = 100 - x #printing the output print (productName + "is available for Rs. " + productPriceAfterDiscount + ".")
In the example above, we have assigned an integer value to variable ‘productPrice’, but in print statement, we are trying to use it as an array.
To resolve this error, you need to avoid using integer type values as an array.
#Code without error #User input start productName = input("Enter product name : ") productPrice = input("Enter product price : ") #User input ends #giving the value of product price to the variable x in int format x = int(productPrice) #calculating the price after discount productPriceAfterDiscount = x - 100 #printing the output print (productName + " is available for Rs. " + str(productPriceAfterDiscount) + " after discount.")
How to avoid this Error
You can avoid this error if you keep the following points in your mind:
- Always use a sensible and meaningful variable name
- Name of the variables should always describe the data they hold
- Dont use variable name same as python in-built function name, module name & constants