Python 布尔表达式和或 [英] Python boolean expression and or

查看:63
本文介绍了Python 布尔表达式和或的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python 中,如果你写类似的东西

In python if you write something like

foo==bar and spam or eggs

如果布尔语句为真,python 似乎返回垃圾邮件,否则返回鸡蛋.有人可以解释这种行为吗?为什么表达式不像一个长布尔值那样被评估?

python appears to return spam if the boolean statement is true and eggs otherwise. Could someone explain this behaviour? Why is the expression not being evaluated like one long boolean?

具体来说,我试图找出为什么会返回垃圾邮件"或鸡蛋"作为表达式结果的机制.

Specifically, I'm trying to figure out the mechanism why 'spam' or 'eggs' is being returned as the result of the expression.

推荐答案

andor 运算符是短路的,这意味着如果表达式的结果可以从只计算第一个操作数推导出,第二个不计算.例如,如果您有表达式 a or b 并且 a 的计算结果为 true,那么 b 是什么并不重要,结果是表达式为真,所以 b 不被计算.它们的实际工作方式如下:

The operators and and or are short-circuiting which means that if the result of the expression can be deduced from evaluating only the first operand, the second is not evaluated. For example if you have the expression a or b and a evaluates to true then it doesn't matter what b is, the result of the expression is true so b is not evaluated. They actually work as follows:

  • a and b:如果 a 为假,则不计算 b 并返回 a,否则返回 b.
  • a or b:如果 a 为真,则不计算 b 并返回 a,否则返回 b.
  • a and b: If a is falsey, b is not evaluated and a is returned, otherwise b is returned.
  • a or b: If a is truthy, b is not evaluated and a is returned, otherwise b is returned.

Falsey 和 truthy 指的是在布尔上下文中评估为 false 或 true 的值.

Falsey and truthy refer to values that evaluate to false or true in a boolean context.

然而,这个和/或习语在没有更好的选择的时代很有用,但现在有更好的方法:

However this and/or idiom was useful back in the days when there was no better alternative, but now there is a better way:

spam if foo==bar else eggs

and/或 idiom 的问题(除了会让初学者感到困惑)是,如果条件为真但垃圾邮件评估为假值(例如空字符串),它会给出错误的结果.因此,您应该避免使用它.

The problem with the and/or idiom (apart from it being confusing to beginners) is that it gives the wrong result if the condition is true but spam evaluates to a falsey value (e.g. the empty string). For this reason you should avoid it.

这篇关于Python 布尔表达式和或的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆