为什么我得不到布尔值?

2024-04-20 03:41:07 发布

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

>>> 'a' in 'aeiou' or 'steve'
True
>>> 'S' in 'Sam' and 'Steve'
'Steve'
>>> 'a' in 'aeiou' and 'steve'
'steve'
>>> 's' in 'aeiou' or 'AEIOU'
'AEIOU'

我正在为一些学生上一堂课,对最后三个结果感到惊讶。我在等布尔值。有人能解释一下吗?你知道吗


Tags: orandintruesam学生steveaeiou
3条回答

表达式的计算方式如下

>>> ('a' in 'aeiou') or ('steve')
True
>>> ('S' in 'Sam') and ('Steve')
'Steve'
>>> ('a' in 'aeiou') and ('steve')
'steve'
>>> ('s' in 'aeiou') or ('AEIOU')
'AEIOU'

orand运算符对表达式求值并返回求值结果。你知道吗

因此,or将首先计算LHSE(左侧表达式),如果它是真的(见下文),它将立即返回计算结果(短路)。只有当它是Falsy(见下文)时,它才会评估并返回RHSE的结果。你知道吗

类似地,and将对LHSE求值,如果是Falsy,它将立即返回值,否则它将返回RHSE的求值结果。你知道吗

真假难辨

引用official documentation。你知道吗

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.

因此,在第一种情况下,('a' in 'aeiou')True,因此它立即返回True。你知道吗

在第二种情况下,('S' in 'Sam')False,因此它返回只对('Steve')求值的结果。你知道吗

在第三种情况下,('a' in 'aeiou')True,因此它返回只对('steve')求值的结果。你知道吗

在最后一种情况下,('s' in 'aeiou')False,因此它返回只对('AEIOU')求值的结果。你知道吗

除此之外,您还可以使用^{}函数来了解表达式是真是假,如下所示

>>> bool('a' in 'aeiou' or 'steve')
True
>>> bool('S' in 'Sam' and 'Steve')
True
>>> bool('a' in 'aeiou' and 'steve')
True
>>> bool('s' in 'aeiou' or 'AEIOU')
True

因为:

'a' in somestring or 'steve'

解释为:

('a' in somestring) or 'steve'

它要么给你True要么给你'steve',这取决于a是否在somestring。它是为'aeiou'而不是为'xyzzy'

>>> 'a' in 'aeiou' or 'steve'
True
>>> 'a' in 'xyzzy' or 'steve'
'steve'

如果要检查字母是否在任何一个单词中,请使用:

('a' in 'aeiou') or ('a' in 'steve')

布尔运算

x或y |如果x为假,那么y,否则x

演示

>>> 0 or 1
1
>>> 0 or 0
0

x和y |如果x为假,那么x,否则y

演示

>>> 0 and 1
0
>>> 1 and 0
0
>>> 1 and 1
1
>>> 

注意: 这些人只在他们的结果需要的时候评估他们的第二个论点。你知道吗


当条件满足时,它将返回True,否则False。你知道吗

演示:

>>> "a" in "abc"
True
>>> "a" in "xyz"
False
>>> 

关于我们的声明:

1.As'a' in 'aeiou'返回True值,我们正在执行or操作,因此这将返回True,因为表达式的第一个(左)值是True。你知道吗

演示:

>>> 'a' in 'aeiou'
True
>>> 'a' in 'aeiou' or 'steve'
True
>>> 

2.作为'S' in 'Sam'返回True,我们正在执行and操作,因此这将从表达式返回第二个值。你知道吗

演示:

>>> 'S' in 'Sam'
True
>>> 'S' in 'Sam' and 'Steve'
'Steve'
>>> 

3.与第二条语句相同。你知道吗

4.作为's' in 'aeiou'返回False,我们正在执行or操作,因此这将从表达式返回第二个值。你知道吗

演示:

>>> 's' in 'aeiou'
False
>>> 's' in 'aeiou' or 'AEIOU'
'AEIOU'
>>> 

相关问题 更多 >