【问题标题】:Many logical 'AND' operators in a row in PythonPython中连续的许多逻辑'AND'运算符
【发布时间】:2018-03-03 06:44:03
【问题描述】:

从空闲:

>>> a=True
>>> b=True
>>> c=True
>>> d=True
>>> e=True
>>> f=a and b and c and d and e
>>> f
True
>>> b = False
>>> f
True

第二个f 不应该是假的,因为 b 是假的吗?

'如果两个操作数都为真,则条件为真。'

https://www.tutorialspoint.com/python/logical_operators_example.htm

即使它一次比较两个名字,因为一个比较给出了 False,所以其他所有比较都会是 False...?

【问题讨论】:

  • f 会是 False 吗?因为b?我没明白你的意思。我认为您错过了部分代码。
  • f 只有当 a,b,c,d 和 e 为真时才为真?没有?
  • 在将b 设置为False 后重复此操作:f=a and b and c and d and e
  • 虽然教程点的引用是正确的,但它也具有误导性的不完整性。 p and q 将返回 q 如果 ptruth-ish 否则 p。 Python 将 __bool__() 方法返回 true 的任何对象视为 true。例如3 and [] 将返回[]

标签: python logical-operators


【解决方案1】:

f 在末尾打印时,它仍然是您第一次将其分配给f 时的值。在您进行评估后更改 b 不会影响 f 的值。

在更改b 的值后,您必须再次执行f=a and b and c and d and e,才能对f 产生任何影响:

>>> a=True
>>> b=True
>>> c=True
>>> d=True
>>> e=True
>>> f=a and b and c and d and e
>>> f
True
>>> b = False
>>> f
True
>>> f=a and b and c and d and e
>>> f
False

【讨论】:

    【解决方案2】:

    变量 f 设置为条件语句在运行时的状态。因此,因为在定义 f 时条件评估为 True,所以 f 将继续为真,直到它被重新分配。它不会在每次调用 f 时重新处理条件。

    【讨论】:

      猜你喜欢
      • 2013-08-14
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多