python短路逻辑_Python支持短路吗?

算子的短路行为and, or:

让我们首先定义一个有用的函数,以确定是否执行了某项操作。一个简单的函数,它接受一个参数,打印一条消息并返回输入,没有变化。

>>> def fun(i):

...     print "executed"

...     return i

...

我们可以观察到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

注:解释器认为以下值表示false:

False    None    0    ""    ()    []     {}

功能短路行为:any(), all():

Python的any()和all()功能还支持短路.如docs所示,它们按顺序计算序列的每个元素,直到找到允许在计算中早期退出的结果。考虑下面的例子来理解这两种情况。

功能any()检查是否有任何元素为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

功能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

连锁比较中的短路行为:

此外,在Python中

比较可以被任意链接。;例如,x < y <= z等于x < y and y <= z,除了y只计算一次(但在这两种情况下)z时,则根本不进行评估。x < y被发现是假的)。

>>> 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

编辑:

还有一点值得注意:-逻辑and, orPython中的运算符返回操作数的价值而不是布尔(True或False)。例如:

操作x and y给出结果if x is false, then x, else y

与其他语言不同的是。&&, ||C中返回0或1的运算符。

例子:

>>> 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

类似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 ()

()

那么,这有什么用呢?中给出的一个示例使用实用Python马格努斯·利·赫特兰:

假设用户应该输入他或她的名字,但是可以选择不输入任何内容,在这种情况下,您需要使用默认值''..您可以使用if语句,但也可以非常简洁地说明:

In [171]: name = raw_input('Enter Name: ') or ''

Enter Name:

In [172]: name

Out[172]: ''

换句话说,如果RAW_INPUT的返回值为true(而不是空字符串),则将其赋值为name(不变);否则,默认''分配给name.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值