首页 > 解决方案 > 如何在“while”循环python 3中使用“or”和“not”

问题描述

我正在尝试使用whileand notor但由于某种原因我的代码不起作用。

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 循环将继续并重复。我究竟做错了什么?

标签: pythonpython-3.x

解决方案


一种写法是这样的:

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子句,告诉用户他们的输入未被识别)。


推荐阅读