Python中的'and'和'or'语句有什么不同?

2024-06-02 04:30:14 发布

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

如果你看本文件:你知道吗

>>>a = "hello"
>>>b = "world"
>>>print a and b 
world
>>>print b and a
hello

以及本文件:你知道吗

>>>a = "hello"
>>>b = "world"
>>>print a or b 
hello
>>>print b or a
world

两者几乎相似。那么它们有何不同呢?你知道吗


Tags: orand文件helloworldprint
1条回答
网友
1楼 · 发布于 2024-06-02 04:30:14

orand运算符短路。当结果确定时,他们会提早回来。你知道吗

对于or,这意味着如果第一个表达式是True,那么查看第二个表达式就没有意义了,因为它无关紧要:

>>> 'a' or 'b'
'a'
>>> False or 'b'
'b'

这同样适用于and,但仅当第一个值计算为False;在这种情况下,表达式总是计算为False,无论第二个表达式的结果如何:

>>> False and 'b'
False
>>> 'a' and 'b'
'b'

Boolean expressions

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.

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

相关问题 更多 >