python笔记(七) - and和or

使用 and 时,在布尔上下文中从左到右演算表达式的值。0''[](){}None 在布尔上下文中为假;其它任何东西都为真。如果所有的值都为真,or 返回最后一个真值。

>>> 'a' and 'b'         
'b'
>>> '' and 'b'          
''
>>> 'a' and 'b' and 'c' 
'c'

 使用 or 时,在布尔上下文中从左到右演算值,就像 and 一样。如果有一个值为真,or 立刻返回该值。

如果所有的值都为假,or 返回最后一个假值。

>>> 'a' or 'b'          
'a'
>>> '' or 'b'           
'b'
>>> '' or [] or {}      
{}
>>> def sidefx():
      
print "in sidefx()"
      
return 1
>>> 'a' or sidefx()     
'a'

python中的a?b:c技巧

>>> def main(syng):
    
print syng and "first" or "second"
>>> main(1)
first
>>> main(0)
second
>>> 

 and-or 技巧无效的场合

>>> def main(syng):
    
print syng and "" or "second"
>>> main(1)
second
>>> main(0)
second
>>> 

 安全使用 and-or 技巧

>>> def main(syng):
    
print (syng and [""or ["second"])[0]
>>> main(0)
second

>>> main(1)

>>> 

posted @ 2009-04-27 11:50  ________囧丶殇  阅读(136)  评论(0编辑  收藏  举报