按'n'后,为什么这个程序不会停止?

时间:2017-06-11 20:36:05

标签: python

为什么输入“n”时不会停止? 我已尝试在底部使用break,但是我犯了错误。这是我遇到的常见问题。我不知道为什么我会被打破。

import random

def game():

  secret_num = random.randint(1, 10)
  guesses = []
  while len(guesses) < 5:
    try:
      guess = int(input("Guess a number between 1 and 10: "))
    except ValueError:
      print("{} isn't a number".format(guess))
    else:
        if guess == secret_num:
          print("You got it! The number was {}.".format(secret_num))
          break
        elif guess < secret_num:
          print("My number is higher than {}".format(guess))
        else:
          print("My number is lower than {}".format(guess))
        guesses.append(guess)
  else:
    print("You didn't get it! My number was {}".format(secret_num))
  play_again = input("Do you want to play again? Y/n ")
  if play_again.lower() != 'Y':
    game()
  else:
    print("Bye!")
game()

1 个答案:

答案 0 :(得分:3)

您将play_again转换为小写字母,但将其与大写字母进行比较。

您只需将其更改为:

if play_again.lower() != 'n':  # 'y' was wrong, right?
    game()
else:
    print("Bye!")
    return    # works also without the explicit return but it makes the intention clearer.