1

由于某种原因,while 循环永远不会中断,就好像 userGuess 永远不会等于 compAnswer。我让它在一开始就打印答案,所以我们知道。在 Pythonista 上完成。

def guessing_game():
    compAnswer = random.randint(1,10)
    print compAnswer
    guesses = 1
    print "Okay, I\'m thinking of a number between 1 and 10."
    userGuess = raw_input("What number am I thinking of?:  ")
    while userGuess != compAnswer:
        userGuess = raw_input("Nope!  try again:  ")
        guesses += 1
    playAgain = raw_input("You got it!  My number was %s and it took you %d guesses.  Play again?:  " % (compAnswer, guesses))
    if playAgain == "yes":
        guessing_game()
    else:
        print "Okay bye!"
4

2 回答 2

3

compAnswer是整数,userGuess是字符串;如果您希望它们相等,请使用相同的类型:

while userGuess != str(compAnswer):
于 2014-04-01T18:20:37.210 回答
0

compAnswer 是一个整数,而 userGuess 是 raw_input() ,它从命令行接受字符串值,所以它们不是相同的数据类型,所以永远不会是 == 所以它会继续循环。在第 6 行试试这个:

userGuess = int(raw_input("What number am I thinking of?: "))

但是您接受的输入始终是数字类型,如果他们键入非数字字符,这可能会中断,所以更好的是,您可以通过将该行放在 try 块中来验证用户输入,并捕获 ValueError:

try: userGuess = int(raw_input("What number am I thinking of?: ")) except ValueError: print "invalid input"

于 2014-04-01T18:34:11.810 回答