所以while循环应该让用户输入两个可用选项(y/n)中的一个,但是如果我输入任何内容,则显示为不正确。
我试过换了! a =和其他一些微小的东西,但没有做任何事情。
print("Hello there " + str(name) + ", are you ready for your
adventure? Y/N")
adventure = input()
while adventure.lower() != "y" or "n":
print(str(name) + " ,that's not a choice. I'll ask again, are
you ready for your adventure? Y/N")
adventure = input()
if adventure.lower() == "n":
print("Cowards take the way out quickly.")
breakpoint
else:
print("Come, you will make a fine explorer for the empire!")
它不是语法错误,但它是一个逻辑错误。
分析解答
将您的if语句更改为:
print("Hello there " + str(name) + ", are you ready for your
adventure? Y/N")
adventure = input()
while adventure.lower() not in ("y", "n"): # <<<<<---- This line changed
print(str(name) + " ,that's not a choice. I'll ask again, are
you ready for your adventure? Y/N")
adventure = input()
if adventure.lower() == "n":
print("Cowards take the way out quickly.")
breakpoint
else:
print("Come, you will make a fine explorer for the empire!")
这是由于Python3中的比较方式。见这里
您可以对代码进行的其他一些修复:
adventure = input("Hello there {}, are you ready for your adventure? Y/N".format(name)) #Added prompt to input, using string formatting.
while adventure.lower() not in ("y", "n"): # <<<<<---- Check input against tuple, instead of using `or` statement
adventure = input(" {}, that's not a choice. I'll ask again, are you ready for your adventure? Y/N".format(name)) #Same as first line
if adventure.lower() == "n":
print("Cowards take the way out quickly.")
break
else:
print("Come, you will make a fine explorer for the empire!")