错误:“int”对象不可编辑?

2024-04-25 21:30:31 发布

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

我已经想办法解决这个错误,但没有成功。这主要是因为我不迭代代码中的任何内容,可能除了count变量,除非在我调用的库函数中存在隐式迭代。为什么我得到这个错误?在

import random
import math
rand = random.randint
floor = math.floor
count = 0
pastGuesses = None
ans = 0
success = False
low = 1
high = 100
player = ""

def initC():
    "Initialize the game mode where the user guesses."
    print "I will come up with a number between 1 and 100 and you have to guess it!"
    answer = rand(1, 100)
    player = "You"
    return answer
def guessEvalC(answer, g):
    "Pass the real answer and the guess, prints high or low and returns true if guess was correct."
    if g == answer:
        print "Correct!"
        return True, 1, 100
    elif g > answer:
        print "Too high!"
        return False, 1, 100
    else:
        print "Too low!"
        return False, 1, 100
def guessC(a, b):
    "Prompt user for a guess."
    suc = 0
    print "%u)Please enter a number." % (count)
    while True:
        try:
            gu = int(raw_input())
            if gu <= 100 and gu >= 1:
                return gu
            print "Outside of range, please try again."
        except ValueError:
            print "NAN, please try again."
def initU():
    "Initialize the game mode where the computer guesses."
    print "Think of a number between 1 and 100, and I'll guess it!"
    player = "I"
    return 0
def guessEvalU(a, b):
    "Prompt user for correctness of guess"
    print "Is this high, low, or correct?"
    s = raw_input()
    value = s[0]
    if value == "l" or value == "L":
        return False, b, high
    elif value == "h" or value == "H":
        return False, low, b
    else:
        return True
def guessU(l, h):
    "Calculations for guess by computer."
    guess = int(floor((l + h)/2))
    print "I guess %u!" % (guess)
    return guess
print "Guessing game!\nDo you want to guess my number?"
resp = raw_input("Yes or no. ")
mode = resp[0]
if mode == "y" or mode == "Y":
    init = initC
    guess = guessC
    guessEval = guessEvalC
else:
    init = initU
    guess = guessU
    guessEval = guessEvalU
ans = init()
while success != True:
    count = count + 1
    gue, low, high = guess(low, high)
    success = guessEval(ans, gue)
print "%s guessed it in %u tries!" % (player, count)
raw_input()

我在第77行得到错误,是因为不能在元组中混合类型吗?在

^{pr2}$

编辑:当我写这篇文章时,我已经切换了几个函数调用,guessEval()是应该返回3项的函数,而guess只返回1。我得到'int' object not iterable错误的原因是,当您试图将返回值赋给变量元组时,解释器假设函数返回的对象将是iterable对象。guess()只返回一个int类型的值,当解释器试图遍历返回的对象并将其内容放入所需的变量中时,它返回这个错误。如果编译器/解释器在返回与某个对象有关的错误时,能够指出错误消息所指的对象,这将很有帮助。例如'int'(returned from guess()) object not iterable。作为一个功能不是很必要,但它会非常有用。在


Tags: orandtheanswerfalsereturnifmode
2条回答

guessC和guessU都只返回一个值,但在第77行中尝试解压3个值。在

调用guess-等待函数返回3个值:

gue, low, high = guess(low, high)

函数返回语句:

^{pr2}$

以及:

return guess

guessC中:

gu = int(raw_input())
return gu

在主回路中:

^{pr2}$

所以,你试图从一个只返回一个的函数中得到三个答案。在

guessC()返回iterable,或在主循环中分配给单个int。在

相关问题 更多 >