While循环将正确答案显示为不正确

时间:2019-07-08 17:55:41

标签: python python-3.x

因此,while循环应该使用户输入两个可用选项之一(y / n),但是如果我输入任何内容,则显示为错误。

我尝试更改!到=和其他一些微小的事情,但是什么也没做。

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!")

这不是语法错误,而是逻辑错误。

2 个答案:

答案 0 :(得分:1)

将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中如何进行比较。参见here

您可以对代码进行其他一些修复:


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!")

请参见usage of python input commandstring formatting

答案 1 :(得分:0)

他们以问题的方式检查了“ y”或“ n”。这样的事情会起作用:

name = 'bob'
print("Hello there " + str(name) + ", are you ready for your adventure? Y/N")
adventure = input().lower()
while adventure not in  {"y","n"}:
    print(str(name) + " ,that's not a choice. I'll ask again, are you ready for your adventure? Y/N")
    adventure = input().lower()
if adventure == "n":
    print("Cowards take the way out quickly.")
    breakpoint
else:
    print("Come, you will make a fine explorer for the empire!")