tom790 tom790 - 5 months ago 261
Python Question

Python - TypeError: 'int' object is not subscriptable (SOLVED)

I have written some code:

def ICP(x):
numofrepeat=0
warning=0
while numofrepeat<len(str(x)) or (x[numofrepeat]==2) or x[numofrepeat]==3) or (x[numofrepeat]==5) or (x[numofrepeat]==7):
if (x[numofrepeat]==0):
warning=warning+1
if warning>1:
numofrepeat=len(x)+1
if warning>1:
return("false")
else:
return("true")


After running it, Python gives me an error:

TypeError: 'int' object is not subscriptable


What should I do?

I know, that:

The result of ICP(121) is true. The result of ICP(999) is false.

Full error:

Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
ICP(999)
File "<location>", line 5, in ICP
if (x[numofrepeat]==0): TypeError: 'int' object is not subscriptable
enter code here


EDIT 1: After Moses Koledoye's answer I changed code to it:

def ICP(x):
numofrepeat=0
warning=0
x_str = str(x)
while x_str[numofrepeat]=='2' or x_str[numofrepeat]=='3' or _str[numofrepeat]=='5' or x_str[numofrepeat]=='7':
if (x[numofrepeat]==0):
warning=warning+1
if warning>1:
numofrepeat=len(x)+1
if warning>1:
return("false")
else:
return("true") But now it is always true. Where is this mistake :?

Answer

The problem should seem clear enough from the error:

TypeError: 'int' object is not subscriptable

Objects of type int are neither iterable nor subscriptable. I really don't know why you want to index x since you're apparently passing an integer.

You can simply test the integer directly:

x==2 or x==3 or x==5 or x==7

And if x is an integer with more than one digit, and you intend to test a digit at an order, you can do:

x_str = str(x)
x_str[numofrepeat]=='2' or x_str[numofrepeat]=='3' or x_str[numofrepeat]=='5' or x_str[numofrepeat]=='7'

With this conversion to string, x becomes subscriptable, and indexing works as long as numofrepeat is not greater or equal to the length of x.

Comments