-2

我一直在寻找解决此错误的方法,但无济于事。这主要是因为我不会迭代代码中的任何内容,除了 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 行收到错误,是因为您不能在元组中混合类型吗?

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

编辑:当我写这篇文章时,我已经切换了几个函数调用guessEval(),是应该返回 3 个项目的函数,而猜测只返回 1。我收到'int' object not iterable错误的原因是当你尝试将返回值分配给变量的元组,解释器假定函数返回的对象将是一个可迭代的对象。 guess()只返回一个 int 类型的值,当解释器尝试遍历返回的对象并将其内容放入所需的变量时,它会返回此错误。如果编译器/解释器在返回与某个对象有关的错误时会提及错误消息所指的对象,那将很有帮助。例如'int'(returned from guess()) object not iterable. 作为一个功能并不是真正必要的,但它会非常有用。

4

2 回答 2

1

guessC

gu = int(raw_input())
return gu

在主循环中:

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

因此,您试图从只返回一个的函数中接收三个答案。

在主循环中返回一个可迭代对象guessC()或分配给一个。int

于 2013-09-30T22:46:33.040 回答
1

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

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

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

函数返回语句:

return gu

和:

return guess
于 2013-09-30T22:47:25.253 回答