【问题标题】:Python: how if is handled?Python:如果如何处理?
【发布时间】:2013-09-21 14:22:32
【问题描述】:

能否请您告知python如何运行多个术语?

例如:

   a = 0
   b = 0
   c = 0

   if a == 0 and b == 1 and c == 0:
   # test fails

我猜 python 在内部将测试分成 3 个 if。 但是,有两种可能的情况:

  • python一个一个运行所有3个,如果有一个是错误的,测试失败
  • 或者python一个一个运行,如果第一次失败,测试失败,其他的如果没有运行

python如何在内部运行这个测试?

谢谢和问候, 雨果

【问题讨论】:

  • 短路了...即第一个条件满足条件使得测试失败...
  • 确切地说,这不是if 子句的属性,而是and / or 运算符的属性。
  • 感谢您的快速解答

标签: python boolean short-circuiting


【解决方案1】:

Python 对if 使用“惰性求值”: 见docs

"表达式 x 和 y 首先计算 x;如果 x 为假,则其值为 回来;否则,对 y 求值,结果值为 回来了。”

【讨论】:

  • 我不确定说 python 使用惰性求值是否正确。 OP if 语句懒惰地评估条件,是的。这里的正确术语是en.wikipedia.org/wiki/Short-circuit_evaluation
  • 来自 wiki:在默认使用惰性求值的语言中(如 Haskell),所有函数实际上都是“短路”的,不需要特殊的短路运算符。
【解决方案2】:

这与条件子句无关,而是布尔运算符andor。他们是short-circuit operators。如果第一个值为 False,则立即使用 False。否则,计算第二个值。

这是一个很好的例子:

>>> def a():
...     print 'a is running!'
...     return True
... 
>>> def b():
...     print 'b is running!'
...     return False
... 
>>> def c():
...     print 'c is running!'
...     return True
... 
>>> if a() and b() and c():
...     print 'hello!'
... 
a is running!
b is running!

因为b 返回Falsec 不会因为不需要而最终运行。

【讨论】:

    【解决方案3】:

    andshort-circuit operator

    如果第一个参数是True,则计算第二个参数。同样,对于后续参数。

    【讨论】:

      【解决方案4】:

      第二个。 and/or 是短路运算符 - 如果不需要,则不计算第二个参数。请参阅文档boolean-operations-and-or-not

      【讨论】:

        猜你喜欢
        • 2022-08-23
        • 2021-03-06
        • 2023-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-11
        • 2018-08-11
        • 1970-01-01
        相关资源
        最近更新 更多