Python冒险游戏 - >在一个while循环中选择A或B不起作用!

1 python loops if-statement while-loop

我正在尝试用Python创建一个简单的冒险游戏.我已经到了需要询问用户是否希望选择选项A或B并使用while循环来尝试执行此操作的点:

AB = input("A or B?")

while AB != "A" or "a" or "B" or "b":
    input("Choose either A or B")

if AB == "A" or "a":
    print("A")
elif AB == "B" or "b":
    print("B")
Run Code Online (Sandbox Code Playgroud)

问题是,无论你输入什么,都会出现"选择A或B"的问题.我究竟做错了什么?

atp*_*atp 5

您的while声明正在评估条件or,对于您提供的字符串,该条件始终为true.

while AB != "A" or "a" or "B" or "b":
Run Code Online (Sandbox Code Playgroud)

手段:

while (AB != "A") or "a" or "B" or "b":
Run Code Online (Sandbox Code Playgroud)

非空字符串始终为True,因此写入or "B"始终为真,并始终要求输入.最好写:

while AB.lower() not in ('a','b'):
Run Code Online (Sandbox Code Playgroud)