编程语言
首页 > 编程语言> > Python短路的价值是什么?

Python短路的价值是什么?

作者:互联网

我正在学习名为《数据结构与技术》的书. Python中的算法.

在介绍逻辑运算符的第12页上,它写道:

The and and or operators short-circuit, (I thinks it should add is called), in that they do not evaluate the second operand if the result can be determined based on the value of the first operand.

This feature is useful when constructing Boolean expressions in which we first test that a certain condition holds (such as a reference not being None), and then test a condition that could have otherwise generated an error condition had the prior test not succeeded.

我对这段话有一些疑问:

>我不明白第二段的确切含义.在C语言中,我们可以将&&(逻辑和)用作以下表达式:
(i!= 0)&& (j / i> 0)以防止被零除的误差.因此,我是否可以在Python中使用表达式(i!= 0)和(j / i> 0)作为C来获得相同的效果?我对段落的理解正确吗?
>如第二段所述,构造布尔表达式的用途是什么?
>最后一个问题是关于在第二段中先前测试未成功的语法.我这应该是“可以使先前测试失败的错误条件”,对吗?

解决方法:

我记得,短路是指编译器优化.如您所知,在AND条件中,如果第一个条件为false,则不对第二个表达式求值.毕竟有什么意义?整体表达式不能为true,因为第一个条件已经为false.同样,使用OR逻辑,只要一个条件为真,则整个OR表达式为真.这归结为节省运行时间.表达式可以不计算,因此不会消耗任何CPU周期.

顺便说一句,我在bash编程中一直使用OR短路.例如,如果前面的条件为false,则以下表达式对于运行函数很有用:

[ $# -ge 2 ] || errexit "You have not supplied enough parameters"

在上面的示例中,仅当命令行中没有2个或更多参数时才会调用errexit.当然,在我的示例中,我并不关心性能.相反,我正在使用||.短路逻辑作为语法糖.

就是这样:在一个紧密循环中,在性能很重要的地方,您可以确定不会不必要地对表达式进行求值.但是在您为&&描述的示例中为了避免被零除,可以使用嵌套的IF语句轻松地编写该代码.再次,它是样式选择,而不是性能考虑.

话虽如此,让我一次回答您的问题:

I can’t understand exact meaning of the second paragraph. In C, we can use the &&(logical and) as the following expression: (i != 0) &&
(j / i > 0) to prevent the error of a division by zero. So then, could
I use the expression (i != 0) and ( j / i > 0) in Python as C to get
the same effect? Is my understanding to the passage right?

你是对的.

What’s the usage of or as a short-circuit to constructing Boolean expressions as said in the second paragraph ?

正如我在上面详细解释的:性能和语法糖(即,更少的键入和更短的表达式;习惯用语).

The final question is about the grammar of had the prior test not
succeeded in the second paragraph. I this it should be “an error
condition that can had the prior test not succeeded”, am I right?

我同意你的看法,措词可能更好.但是当您尝试表达它时,您会发现这很难做(实际上,您的建议无效).基本上,您的避免零错误除法的示例是作者尝试说明的完美示例.这是我的尝试:短路逻辑对于检查表达式的前置条件很有用,如果不满足这些条件,这些前置条件可能会产生错误.

标签:python,logical-operators,short-circuiting
来源: https://codeday.me/bug/20191013/1908494.html