>>> ('a' in 'aeiou') or ('steve')
True
>>> ('S' in 'Sam') and ('Steve')
'Steve'
>>> ('a' in 'aeiou') and ('steve')
'steve'
>>> ('s' in 'aeiou') or ('AEIOU')
'AEIOU'
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
表达式的计算方式如下
or
和and
运算符对表达式求值并返回求值结果。你知道吗因此,
or
将首先计算LHSE(左侧表达式),如果它是真的(见下文),它将立即返回计算结果(短路)。只有当它是Falsy(见下文)时,它才会评估并返回RHSE的结果。你知道吗类似地,
and
将对LHSE求值,如果是Falsy,它将立即返回值,否则它将返回RHSE的求值结果。你知道吗真假难辨
引用official documentation。你知道吗
因此,在第一种情况下,
('a' in 'aeiou')
是True
,因此它立即返回True
。你知道吗在第二种情况下,
('S' in 'Sam')
是False
,因此它返回只对('Steve')
求值的结果。你知道吗在第三种情况下,
('a' in 'aeiou')
是True
,因此它返回只对('steve')
求值的结果。你知道吗在最后一种情况下,
('s' in 'aeiou')
是False
,因此它返回只对('AEIOU')
求值的结果。你知道吗除此之外,您还可以使用^{} 函数来了解表达式是真是假,如下所示
因为:
解释为:
它要么给你
True
要么给你'steve'
,这取决于a
是否在somestring
。它是为'aeiou'
而不是为'xyzzy'
:如果要检查字母是否在任何一个单词中,请使用:
布尔运算
x或y |如果x为假,那么y,否则x
演示
x和y |如果x为假,那么x,否则y
演示
注意: 这些人只在他们的结果需要的时候评估他们的第二个论点。你知道吗
当条件满足时,它将返回
True
,否则False
。你知道吗演示:
关于我们的声明:
1.As
'a' in 'aeiou'
返回True
值,我们正在执行or
操作,因此这将返回True
,因为表达式的第一个(左)值是True
。你知道吗演示:
2.作为
'S' in 'Sam'
返回True
,我们正在执行and
操作,因此这将从表达式返回第二个值。你知道吗演示:
3.与第二条语句相同。你知道吗
4.作为
's' in 'aeiou'
返回False
,我们正在执行or
操作,因此这将从表达式返回第二个值。你知道吗演示:
相关问题 更多 >
编程相关推荐