TypeError: 'float' object is not subscriptable
In this article we will learn about the TypeError: 'float' object is not subscriptable.
This error occurs when we try to access a float type object using index numbers.
Non subscriptable objects are those whose items can't be accessed using index numbers. Example float, int, etc.
Examples of subscriptable objects are strings, lists, dictionaries. Since we can access items of a strings, lists or a dictionaries using index numbers. Float object is not indexable and thus we can't access it using index numbers.
Let us understand it more with the help of an example.
Example:
# Program for finding area of a circle
radius = int(input("Enter radius of a circle :"))
pi=3.14
area = pi*radius*radius
print("area of the circle :",area[0])
Output:
Enter radius of a circle :3
File "area.py", line 5, in <module>
print("area of the circle :",area[0])
TypeError: 'float' object is not subscriptable
In the above example we are trying to access the value at index 0 but as discussed above float is not indexable.
So accessing using index number will raise an error.
TypeError: 'float' object is not subscriptable.
Solution:
Do print("area of the circle :",area) instead of print("area of the circle :",area[0]) in line 10 of the code.
But what if we only want the value at index 0 and not the whole answer?
To solve this issue we can change the non subscriptable object to a subcriptable object.
In this case, we can try changing the float object to a string. As shown below.
Example:
# Program for TypeError: 'float' object is not subscriptable
radius = int(input("Enter radius of a circle :"))
pi=3.14
area = pi*radius*radius
# Area of the circle
print("area of the circle :",area)
# Converting float to string and printing value at index 0
print("value at index 0 :",str(area)[0])
Output:
Enter radius of a circle :3
area of the circle : 28.259999999999998
value at index 0 : 2