首页 > 解决方案 > Python 中的条件“或”运算符未正确验证

问题描述

status= None
if 'Up' or 101 in status:
    print "Inside If statement"
else:
    print "Inside Else Statement"

代码流进入“If”循环并打印“Inside If Statement”。状态实际上是 None 并且通过阅读代码它应该打印“Inside Else Statement”。我可以修改验证部分并使其在 else 语句中执行。但我想知道这种情况下如何返回“真”

if 'Up' or 101 in status:

标签: python-2.7

解决方案


Python 中的字符串是假的,也就是说一个空字符串 ( '') 等价于False,而其他的则是True

您的条件被评估为(括号仅用于解释目的)

if ('Up') or (101 in status):

而且因为'Up'总是True它总是会进入if块内。

你可以改为写:

if 'Up' in status or 101 in status:

或者更通用的方法any是:

if any(x in status for x in ('Up', 101)):

您可以在此问题中找到更多答案


推荐阅读