5

如果两个条件都为真,我知道逻辑上and用于布尔值评估为真,但我对以下语句有疑问:

print "ashish" and "sahil"

it prints out "sahil"?
 another example:
 return s[0] == s[-1] and checker(s[1:-1])
 (taken from recursive function for palindrome string
 checking            
please explain it and other ways and is oveloaded ,especially what the second statement do.
4

3 回答 3

10

and没有超载。

在您的代码中,"ashish"是一个真实值(因为非空字符串是真实的),所以它评估"sahil". as"sahil"也是一个真值,"sahil"返回到 print 语句然后被打印。

于 2013-09-05T19:21:55.740 回答
7

x and y基本上意味着:

return y,除非x是 False-ish - 在这种情况下 returnx

以下是可能的组合列表:

>>> from itertools import combinations
>>> items = [True, False, 0, 1, 2, '', 'yes', 'no']
>>> for a, b in combinations(items, 2):
    print '%r and %r => %r' % (a, b, a and b)


True and False => False
True and 0 => 0
True and 1 => 1
True and 2 => 2
True and '' => ''
True and 'yes' => 'yes'
True and 'no' => 'no'
False and 0 => False
False and 1 => False
False and 2 => False
False and '' => False
False and 'yes' => False
False and 'no' => False
0 and 1 => 0
0 and 2 => 0
0 and '' => 0
0 and 'yes' => 0
0 and 'no' => 0
1 and 2 => 2
1 and '' => ''
1 and 'yes' => 'yes'
1 and 'no' => 'no'
2 and '' => ''
2 and 'yes' => 'yes'
2 and 'no' => 'no'
'' and 'yes' => ''
'' and 'no' => ''
'yes' and 'no' => 'no'
于 2013-09-05T19:21:49.710 回答
4

如果 左边的表达式的结果and是假的,它的计算结果就是假的。否则,它会计算其右侧表达式的结果。"ashish"是真实的。

于 2013-09-05T19:22:17.287 回答