如何在"while"循环中使用"or"和"not" python 3



我正在尝试将whilenotor一起使用,但由于某种原因,我的代码不起作用。

orientation = ""
while orientation is not "h" or "v":
    print("Type 'h' for horizontal and 'v' for vertical") 
    orientation = input()
    if orientation == "h":
        do_something()
    if orientation == "v":
        do_something()

预期的结果是,如果我在输入中键入"h"或"v",do_something()将被调用并且 while 循环将结束,但相反,while 循环继续并重复。我做错了什么?

一种写法是这样的:

while orientation not in {"h", "v"}:

或者,由于您已经在循环中检查"h""v",因此您可以避免重复自己:

while True:
    print("Type 'h' for horizontal and 'v' for vertical") 
    orientation = input()
    if orientation == "h":
        do_something()
        break
    if orientation == "v":
        do_something()
        break

(可能将第二个if更改为elif,并选择性地添加一个else子句,告诉用户他们的输入未被识别(。

相关内容

最新更新