【问题标题】:Conditional "or" operator in Python is not validating properlyPython 中的条件“或”运算符未正确验证
【发布时间】:2019-05-30 05:30:16
【问题描述】:
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 语句中执行。但我想知道在这种情况下如何返回“True”

if 'Up' or 101 in status:

【问题讨论】:

    标签: python-2.7


    【解决方案1】:

    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)):
    

    你可以找到更多关于这个in this question的答案

    【讨论】:

    • 感谢您的解释。这部分让我很清楚。 if ('Up') or (101 in status):
    猜你喜欢
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    相关资源
    最近更新 更多