Python TypeError:“int”对象不是subscriptab

2024-10-01 11:31:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一些代码:

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")

运行之后,Python给了我一个错误:

^{pr2}$

我该怎么办?在

我知道,那:

ICP(121)结果正确。 ICP(999)结果为假。在

完全错误:

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”对象不可订阅 在此处输入代码


Tags: or代码inlenreturnifdef错误
1条回答
网友
1楼 · 发布于 2024-10-01 11:31:57

从错误来看,问题应该足够清楚:

TypeError: 'int' object is not subscriptable

int类型的对象既不可编辑也不可订阅。我真的不知道为什么要索引x,因为显然你传递的是一个整数。在

您可以直接测试整数:

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

如果x是一个包含多个数字的整数,并且您打算按顺序测试一个数字,则可以执行以下操作:

^{pr2}$

通过对字符串的转换,x变成了可订阅的,只要numofrepeat不大于或等于x的长度,索引就可以工作。在

相关问题 更多 >