0%

pytho的and返回值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# python的and返回值
"""
在布尔上下文中从左到右演算表达式的值,如果布尔上下文中的所有值都为真,那么 and 返回最后一个值。

如果布尔上下文中的某个值为假,则 and 返回第一个假值。
"""
# 实例1
def re(n):
return n + 1 and n ** 2

print(re(0))#因为非零即假,所以返回第一个表达式的值
print(re(100))# 因为100为真,所以返回后一个表达式的值
# 实例2
"""对于字符串而言,其中有空格的字符串为假,否则为真"""
def st(s):
return s and s.strip()


print(st('happy '))#这里有空格为假的,则返回后一个表达式的值。经过strip方法之后,末尾的空格被剔除了
print(st('names'))# 这里为空格,则直接返回这个字符串
print(st('fa fdaf'))# strip只对首尾的对象管用
"""
输出结果:
0
10000
happy
names
fa fdaf
"""