Python猜猜游戏

时间:2014-04-01 18:19:18

标签: python pythonista

由于某种原因,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!"

2 个答案:

答案 0 :(得分:3)

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

while userGuess != str(compAnswer):

答案 1 :(得分: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"