python - 如何在“while”循环python 3中使用“or”和“not”
问题描述
我正在尝试使用while
and not
,or
但由于某种原因我的代码不起作用。
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
子句,告诉用户他们的输入未被识别)。
推荐阅读
- python - 如何在只有 **kwargs 参数的构造函数中正确使用空列表作为默认参数
- sed - Need to do sed to replace ${D} string in do_install()
- node.js - Webpack 运行没有错误但浏览器为空
- qt - 为什么 QMenu:hover 在 QtDesigner 中不起作用
- bash - 在数据范围bash之间搜索文件
- android - Android 文本中的 dp 或 sp
- r - 有没有办法让 R 中的 flextable 中的单个单元格具有圆角?
- react-native - React Native AdMob:请求的 InterstitialAd 尚未加载且无法显示
- android - 意图getextra中嵌套Parcelable的空指针异常
- c++ - 为什么在cpp中与'World'比较时会打印出'Hello'?