python - 冷凝比较

thi*_*inc 3 python comparison comparison-operators

我是这里的新成员,也是python的新成员.我的问题如下,有一条这样的线是否有效?

if x or y is 'whatever':
Run Code Online (Sandbox Code Playgroud)

我在解释器中测试了这个并且得到了不一致的结果.看起来这条线会产生更一致和预期的结果

if (x or y) is 'whatever':
Run Code Online (Sandbox Code Playgroud)

或者最好是明确地将所有内容都这样布局

if x is 'whatever' or y is 'whatever':
Run Code Online (Sandbox Code Playgroud)

最后一个总是有效,但我只是想让我的代码更简洁,同时仍然遵循最佳实践.我尝试进行搜索,以便不要问多余的问题,但是搜索"是"或"和"并且"相当困难".在此先感谢您的任何帮助.

编辑:感谢大家的快速回复.当我需要'或'时,这对我来说非常有效

if 'whatever' in [x,y]:
Run Code Online (Sandbox Code Playgroud)

但是,如果我需要'和',我将如何缩小它?

if x == 'whatever' and y == 'whatever':
Run Code Online (Sandbox Code Playgroud)

Ned*_*der 8

or 不像英语那样工作.

x or y如果x是真值,则返回x,否则返回y.字符串是真的,如果它们不是空的.

更糟糕的是,"是"的优先级高于"或",所以你的表达方式与之相同x or (y is 'whatever').因此,如果x不为空,则返回x(这将为true,因此if将执行).如果x为空,它将进行评估y is 'whatever'.

BTW:不要使用"is"来比较值相等,使用==.

你想要这个(parens可选):

if (x == 'whatever') or (y == 'whatever'):
Run Code Online (Sandbox Code Playgroud)

或更简洁,但更陌生:

if 'whatever' in [x, y]:
Run Code Online (Sandbox Code Playgroud)

  • 也许我已经这么久了,但我不知道最后一点是多么奇怪. (2认同)