我做了一个简单的战舰游戏。在游戏结束时,无论是以失败的胜利结束,我都希望用户能够再次玩或退出。这段代码打算进行输入,确保它是" y"或" n"如果输入是" n"则设置一个控制初始while循环的变量为false。不知何故,当循环再次运行时,无论我做什么,它都会将输入设置回" y" - 我已经使用print语句检查了它,它肯定被正确设置为" n"但是如果我在while循环之后立即再次打印该值,那么它就是" y。"无论输入如何,while循环都会再次运行。我怎样才能解决这个问题" n"正确退出循环?
restart = "y"
while restart[0] not in ("n", "N"):
def play_again():
print ("")
restart = input("Enter y to play again or n to quit: ")
print ("")
try:
x = str(restart)
except ValueError:
print ("Please enter y or n.")
print ("")
play_again()
else:
if str(restart) != "y" and str(restart) != "n":
print ("Please enter y or n.")
print ("")
play_again()
*game*
play_again()
答案 0 :(得分:-1)
def restart_game():
try:
restart = input("Enter y to play again or n to quit: ")
if restart == "y":
return True
if restart == "n":
return False
raise ValueError
except ValueError:
print ("Please enter y or n.")
return True
while True:
print 'Playing the game ...'
if not restart_game(): break