我正在尝试在python中重新启动我的程序,但是,由于某种原因,代码在while playagain循环中被捕获。它说“这不是一个有效的答案。请输入'是'或'否'。”当我输入yes,no或任何其他可接受的输入时。为什么这不起作用?
while True:
playagain = input("Would you like to play again?")
while playagain != "y" or playagain != "Y" or playagain != "Yes" or playagain != "yes" or playagain != "YES" or playagain != "n" or playagain != "N" or playagain != "No" or playagain != "no" or playagain != "NO":
print("That was not a valid answer. Please enter 'yes' or 'no'.")
playagain = input("Would you like to play again?")
if playagain == "y" or playagain == "Y" or playagain == "Yes" or playagain == "yes" or playagain == "YES":
break
else:
print("Thank you for playing MadLibs!")
答案 0 :(得分:3)
您可以使用lower()
函数和in
运算符来清理代码。
您可以更改此代码:
playagain = input("Would you like to play again?").lower()
while playagain not in ['y', 'yes', 'n', 'no']:
print("That was not a valid answer. Please enter 'yes' or 'no'.")
playagain = input("Would you like to play again?").lower()
这样整个代码就是:
while True:
playagain = input("Would you like to play again?").lower()
while playagain not in ['y', 'yes', 'n', 'no']:
print("That was not a valid answer. Please enter 'yes' or 'no'.")
playagain = input("Would you like to play again?").lower()
if playagain in ['n', 'no']:
print("Thank you for playing MadLibs!")
break
答案 1 :(得分:0)
你想:
while playagain != "y" or playagain != "Y" or playagain != "Yes"
是:
while playagain != "y" and playagain != "Y" and playagain != "Yes"
答案 2 :(得分:0)
你也可以这样做:
while True:
valid_response = ["y","Yes","Y","No","n","N"]
positive_response = ["y","Yes","Y"]
playagain = input("Would you like to play again?")
while playagain not in valid_response:
print("That was not a valid answer. Please enter 'yes' or 'no'.")
playagain = input("Would you like to play again?")
if playagain in positive_response:
printf("You chose to play again"):
break
else:
print("Thank you for playing MadLibs!")
break;
代码中的问题是,while循环中至少有一个句子总是为真。由于playagain
不能同时为"Y"
,"y"
,"Yes"
,"No"
,"n"
和"N"
(对于循环中的条件为假)。