user6537920
user6537920

Reputation:

Python - TypeError: 'int' object is not subscriptable

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

Upvotes: 0

Views: 7949

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78556

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.

Upvotes: 1

Related Questions