本文翻译自:Does Python support short-circuiting?

Python是否支持布尔表达式短路?


#1楼

参考:https://stackoom.com/question/ApD6/Python是否支持短路


#2楼

Short-circuiting behavior in operator and , or : 操作符and的短路行为, or

Let's first define a useful function to determine if something is executed or not. 我们首先定义一个有用的函数来确定是否执行了某些操作。 A simple function that accepts an argument, prints a message and returns the input, unchanged. 一个简单的函数,它接受一个参数,打印一条消息并返回输入,且未更改。

>>> def fun(i):
...     print "executed"
...     return i
...

One can observe the Python's short-circuiting behavior of and , or operators in the following example: 在以下示例中,可以观察Python的 and or运算符的短路行为 :

>>> fun(1)
executed
1
>>> 1 or fun(1)    # due to short-circuiting  "executed" not printed
1
>>> 1 and fun(1)   # fun(1) called and "executed" printed
executed
1
>>> 0 and fun(1)   # due to short-circuiting  "executed" not printed
0

Note: The following values are considered by the interpreter to mean false: 注意:解释器认为以下值表示false:

        False    None    0    ""    ()    []     {}

Short-circuiting behavior in function: any() , all() : 函数中的短路行为: any()all()

Python's any() and all() functions also support short-circuiting. Python的any()all()函数还支持短路。 As shown in the docs; 如文档所示; they evaluate each element of a sequence in-order, until finding a result that allows an early exit in the evaluation. 他们按顺序评估序列中的每个元素,直到找到可以尽早退出评估的结果。 Consider examples below to understand both. 考虑下面的示例以了解两者。

The function any() checks if any element is True. 函数any()检查是否有任何元素为True。 It stops executing as soon as a True is encountered and returns True. 一旦遇到True,它将立即停止执行并返回True。

>>> any(fun(i) for i in [1, 2, 3, 4])   # bool(1) = True
executed
True
>>> any(fun(i) for i in [0, 2, 3, 4])
executed                               # bool(0) = False
executed                               # bool(2) = True
True
>>> any(fun(i) for i in [0, 0, 3, 4])
executed
executed
executed
True

The function all() checks all elements are True and stops executing as soon as a False is encountered: 函数all()检查所有元素是否为True,并在遇到False时立即停止执行:

>>> all(fun(i) for i in [0, 0, 3, 4])
executed
False
>>> all(fun(i) for i in [1, 0, 3, 4])
executed
executed
False

Short-circuiting behavior in Chained Comparison: 链式比较中的短路行为:

Additionally, in Python 此外,在Python中

Comparisons can be chained arbitrarily ; 比较可以任意链接 ; for example, x < y <= z is equivalent to x < y and y <= z , except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false). 例如, x < y <= z等效于x < y and y <= z ,除了y仅被评估一次(但是在两种情况下,当x < y被发现为假时, z都不被评估)。

>>> 5 > 6 > fun(3)    # same as:  5 > 6 and 6 > fun(3)
False                 # 5 > 6 is False so fun() not called and "executed" NOT printed
>>> 5 < 6 > fun(3)    # 5 < 6 is True
executed              # fun(3) called and "executed" printed
True
>>> 4 <= 6 > fun(7)   # 4 <= 6 is True
executed              # fun(3) called and "executed" printed
False
>>> 5 < fun(6) < 3    # only prints "executed" once
executed
False
>>> 5 < fun(6) and fun(6) < 3 # prints "executed" twice, because the second part executes it again
executed
executed
False

Edit: 编辑:
One more interesting point to note :- Logical and , or operators in Python returns an operand's value instead of a Boolean ( True or False ). 一个更有趣的一点需要注意: -逻辑andor运营商在Python返回一个操作数的 ,而不是一个布尔值( TrueFalse )。 For example: 例如:

Operation x and y gives the result if x is false, then x, else y if x is false, then x, else y操作x and y给出结果if x is false, then x, else y

Unlike in other languages eg && , || 与其他语言(例如&&|| operators in C that return either 0 or 1. C中的运算符返回0或1。

Examples: 例子:

>>> 3 and 5    # Second operand evaluated and returned
5
>>> 3  and ()
()
>>> () and 5   # Second operand NOT evaluated as first operand () is  false
()             # so first operand returned

Similarly or operator return left most value for which bool(value) == True else right most false value (according to short-circuiting behavior), examples: 同样or运算符返回最左边的值,其中bool(value) == True否则返回最右边的假值(根据短路行为),示例:

>>> 2 or 5    # left most operand bool(2) == True
2
>>> 0 or 5    # bool(0) == False and bool(5) == True
5
>>> 0 or ()
()

So, how is this useful? 那么,这有什么用呢? One example use given in Practical Python By Magnus Lie Hetland: Magnus Lie Hetland在《 实用Python》中给出的一个示例用法:
Let's say a user is supposed to enter his or her name, but may opt to enter nothing, in which case you want to use the default value '<unknown>' . 假设用户应该输入他或她的名字,但可能选择不输入任何内容,在这种情况下,您要使用默认值'<unknown>' You could use an if statement, but you could also state things very succinctly: 您可以使用if语句,但也可以非常简洁地陈述一下:

In [171]: name = raw_input('Enter Name: ') or '<Unkown>'
Enter Name: In [172]: name
Out[172]: '<Unkown>'

In other words, if the return value from raw_input is true (not an empty string), it is assigned to name (nothing changes); 换句话说,如果raw_input的返回值是true(不是空字符串),则将其分配给name(不变);否则,它将返回true。 otherwise, the default '<unknown>' is assigned to name . 否则,默认的'<unknown>'被分配给name


#3楼

Yes. 是。 Try the following in your python interpreter: 在您的python解释器中尝试以下操作:

and

>>>False and 3/0
False
>>>True and 3/0
ZeroDivisionError: integer division or modulo by zero

or 要么

>>>True or 3/0
True
>>>False or 3/0
ZeroDivisionError: integer division or modulo by zero

#4楼

是的, andor运算符都短路-请参阅docs 。

Python是否支持短路?相关推荐

  1. python短路与_Python支持短路吗?

    运算符中的短路行为and,or: 让我们首先定义一个有用的函数来确定是否执行某些操作. 一个接受参数的简单函数,打印一条消息并返回输入,不变. >>> def fun(i): ... ...

  2. ClewareControl 2.4 发布,传感器控制程序,增加对 python 的支持

    为什么80%的码农都做不了架构师?>>>    ClewareControl 2.4 增加对 python 的支持,可轻松开发使用该接口的相关应用. Clewarecontrol 可 ...

  3. Supporting Python 3(支持python3)——常见的迁移问题

    2019独角兽企业重金招聘Python工程师标准>>> 常见的迁移问题 如果你按照该建议来确保你的代码使用Python 2.7 - 3来运行没有警告,一些现在会遇到的简单错误都是可以 ...

  4. python不支持以下哪种数据类型_Python 不支持以下哪种数据类型?

    Python 不支持以下哪种数据类型? 答:char 中国大学MOOC: 为了充分利用学习时间,下列方法可行的是: 答:尽量选择理想的固定场所学习\n充分利用等候和其它碎片时间\n把握一天中的最佳状态 ...

  5. python显示无效语法怎么处理-Python不支持 i ++ 语法的原因解析

    简要讨论为什么它不提供++作为运算符 正常情况下,当有人问起++原因而不是Python中的运算符时,这一行引起了我的注意. 如果您想知道最初的原因,则必须翻阅旧的Python邮件列表,或询问那里的某个 ...

  6. anaconda新建python2环境安装不了jupyterlab_Anaconda 5.0.0 JupyterLab 0.27.0 中配置多Python环境支持...

    Anaconda 5.0.0 JupyterLab 0.27.0 中配置多Python环境支持 概述 Anaconda 5.0.0 中自带了 JupyterLab 0.27.0 版本,这是 Anaco ...

  7. 下列数据类型中python不支持的是_ 下列选项中 ,Python 不支持的数据类型有 ( ) 。_学小易找答案...

    [单选题] 下列标识符中 , 合法的是 ( ) . [简答题]说明轴承代号7204AC表达的含义. [判断题]type() 函数可以查看变量的数据类型. ( ) [名词解释]限界 [单选题]体育教学 ...

  8. 初学__Python——Python中文支持、Python计算器

    目录 一.Python对中文的支持 二.简单实用的Python计算器 一.Python对中文的支持 在Python中,可以在各种编码间相互转换. 如果在交互式命令中使用中文,即便不做处理,一般也不会出 ...

  9. python不支持字符类型、单个字符也作为字符串使用_Python 字符串

    Python 字符串 字符串是 Python 中最常用的数据类型.我们可以使用引号来创建字符串. 创建字符串很简单,只要为变量分配一个值即可.例如: var1 = 'Hello World!' var ...

最新文章

  1. 新手问题之找不到R文件
  2. win10 远程问题汇总
  3. Tomcat实现session的代码逻辑分析
  4. centos7光盘修复 grub_centos7修复grub2
  5. java的封装和this关键字知识整理
  6. vue生命周期及其应用场景
  7. core dump python_python 源码笔记 ---- freeblock
  8. RecyclerView Widget 使用
  9. Airtest多点触控测试
  10. 快播将关闭QVOD服务器 宅男,你心碎了吗?
  11. SpringBoot集成移动云MAS平台(SDK版本)
  12. HTTP 错误 404.3 - Not Found 由于扩展配置问题而无法提供您请求的页面。
  13. 关系型数据库表之间的联系[关系]详解
  14. Android动画合集
  15. 安裝wgt文件失败[-1205]:WGT安装包中manifest.json文件的version版本不匹配
  16. 美国专利法中方法权要(method)直接侵权的考量
  17. 安卓手机管理器_亿连手机互联连接失败?搞定它
  18. idea的run窗口不显示_IDEA 显示Run Dashboard窗口的2种方式
  19. 前端面试题---html/css
  20. ISO20000认证的意义是什么?

热门文章

  1. zabbix中文乱码设置
  2. 如何分析解读systemstat dump产生的trc文件
  3. Linux的常用基础命令
  4. linux tomcat/bin/shutdown.sh 关闭不了
  5. ModelState对象
  6. XML_CPP_资料_libXml2_01
  7. 为什么事务日志自动增长会降低你的性能
  8. apache 搭建PHP多站点
  9. Web之路笔记之三 - 使用Floating实现双栏样式
  10. ASP.NET MVC:实现我们自己的视图引擎