在Python中,''and'逻辑运算符和“&”位运算符之间有什么区别?

2024-04-27 05:19:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个Python案例: 1) 案例1:

print "AND :", exists("") and os.path.getsize("")

本例将给出一个结果:AND : False

2)案例2:

^{pr2}$

这种情况下会产生如下错误:

Bitwise :
Traceback (most recent call last):
  File "G:\Dropbox\Workspace_Python\PyGUI\default\__init__.py", line 6, in <module>
    print "Bitwise :", exists("") & os.path.getsize("")
  File "C:\Python27\lib\genericpath.py", line 49, in getsize
    return os.stat(filename).st_size
WindowsError: [Error 3] The system cannot find the path specified: ''

你能帮我解释一下这两种情况的区别吗?在


Tags: andpathinpyosexistsline情况
2条回答

逻辑and运算符中,如果第一个表达式是错误的,则不会计算第二个表达式。由于exists("")失败,os.path.getsize("")永远不会在第一种情况下执行。在

但是在&运算符的情况下,两个操作数都必须求值,才能得到结果。由于您不能stat一个无效的文件(以获得大小),它将失败并返回一个错误。在

引用Boolean operations文档

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

还要注意

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

所以,当你评估

exists("") and os.path.getsize("")

exists("")返回False,根据上面引用的文本,它将立即返回False,而不必执行os.path.getsize("")。在

在大多数语言中,逻辑ANDs将"short-circuit"并在第一个参数为false时立即中止(因为不管第二个参数如何,结果都是相同的)。在

在您的示例中,如果您将二进制和(and)翻转为OR(or),则该语言不能短路,因为第一个结果是false,它需要检查第二个结果是否应该返回true或false。在

相关问题 更多 >