Skip to main content
 首页 » 编程设计

python之“int”对象在我的代码中不可订阅

2024年10月17日7webabcd

我正在尝试用 Python 编写一个程序来比较两个 4 位数字,一个由玩家给出,一个由计算机生成,并告诉玩家他们得到了多少头牛和公牛 - 牛是匹配数字在错误的地方和多头在正确的地方匹配数字。每次尝试时,我总是收到 'int' object is not subscriptable 错误。我知道这意味着我需要使 int guess 成为一个字符串,但即使我尝试这样做,它也会在同一个地方给我同样的错误。有什么指点吗?

def how_many_bulls(answer,guess): 
    ''' Returns the number of bulls the guess earns when the secret number 
    is the answer. ''' 
    bulls = 0 
    if guess[0] == answer[0]: 
        bulls = bulls+1 
        if guess[1] == answer[1]: 
            bulls = bulls+1 
            if guess[2] == answer[2]: 
                bulls = bulls+1 
                if guess[3] == answer[3]: 
                    bulls = bulls+1 
    return bulls 

抱歉,如果我的格式有任何错误 - 我是第一次使用该网站。

请您参考如下方法:

您应该将 answer 和 guess 都转换为字符串。

(或者以任何其他方式访问他们的数字,有很多)