如何使用;或;及;不是";在“a”中;而";循环python 3
我正在尝试将如何使用;或;及;不是";在“a”中;而";循环python 3,python,python-3.x,Python,Python 3.x,我正在尝试将while与not和或一起使用,但由于某些原因,我的代码无法工作 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 ==
while
与not
和或一起使用,但由于某些原因,我的代码无法工作
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
子句,告知用户他们的输入未被识别)。一种编写方法如下:
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
子句,告知用户其输入未被识别)。使用方向不在['h','v']
使用方向不在['h','v']