我已经搜索了修复我的错误无效。这主要是因为我不会迭代我的代码中的任何内容,除了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个项目的函数,而guess只返回1.我得到{{1的原因错误是当您尝试将返回值分配给变量元组时,解释器假定函数返回的对象将是可迭代对象。 'int' object not iterable
只返回一个int类型的值,当解释器尝试迭代返回的对象并将其内容放入所需的变量时,它将返回此错误。如果编译器/解释器在返回与某个对象有关的错误时会提到错误消息所指的对象,那将会很有帮助。例如guess()
。作为一个功能并不是必需的,但它会非常有用。
答案 0 :(得分:1)
在guessC
:
gu = int(raw_input())
return gu
在主循环中:
gue, low, high = guess(low, high)
所以,你试图从只返回一个的函数中得到三个答案。
从guessC()
返回一个可迭代,或在主循环中指定一个int
。
答案 1 :(得分:1)
guessC和guessU都只返回一个值,但在第77行,你试图解包3个值。
对guess
的调用 - 等待函数返回3个值:
gue, low, high = guess(low, high)
函数return语句:
return gu
和
return guess