24 Mar 2009

Python学习笔记 - 3:逻辑表达式与三目运算

本文主要有: 逻辑表达式

This article is mainly about Logical Expression

Python的逻辑运算主要有 and/or/XOR(与,或,异或), 全部都是二值运算符,这跟其他语言并无区别.

Python has the same logic operators as other languages, such as AND, OR, XOR. They are all Binary Operators.

求值规则为:

Evaluation rules are:



1    非零数字,非空list, tuple, dict, string都返回TRUE
2    零, None, 空list, tuple, dict, string都返回FALSE


1    Non-zero number, non-empty list, tuple, dict, string return TRUE
2    Zero, None,  empty list, tuple, dict, string return FALSE

运算规则为:

Algorithm are:

1    a and b    如果a为TRUE,返回b;否则返回a
2    a or b      如果a为TRUE,返回a;否则返回b
3    not a       如果a为TRUE,返回FALSE,否则返回TRUE
4    从左到右运算, 有短路行为,也就是说只有在需要时才进一步计算.


1    a and b    return b if a is TRUE; otherwise return a
2    a or b      return a if a is TRUE; otherwise return b
3    not a       return TRUE is a is FALSE; otherwise return TRUE
4    from left to right, short circuit behaviour



具体实例:

Examples:

*** Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32. ***
>>> a = 'a'; b = []; c = 0
>>> bool(a)
True
>>> bool(b)
False
>>> bool(c)
False
>>> bool(not c)
True


Python中没有三目运算符 a?b:c,但是可以用下面的方法来实现:

Python has no ternary operator like a?b:c, but it's also possible to get the same results by:

if a: return b
else: return c


其实更简单的办法是逻辑运算符连用:

Actually, there is another simple method:

a and b or c


但是要注意: 如果b为FALSE,则不能用这个表达,
原因见上面关于Python计算and or的求值及运算规则.

NOTE: if b is FALSE, it can not be applied any more.

测试如下:

Test:

>>> if a=='a': print b
... else: print c
... 
[]
>>> print a=='a' and b or c
0
>>> b.append('b')
>>> b
['b']
>>> bool(b)
True
>>> print a=='a' and b or c
['b']


来分析下上面的三目运算, a and b or c:

Following is the analysis:

a and b or c <=> (a and b) or c
1        计算a and b, 如果a为true,返回b,
1.1            如果b为TRUE,整个(a and b)为TRUE,否则为FLASE
2        计算(a and b) or c
2.1            如果a为TRUE,(a and b)返回b,继续计算b的逻辑值
如果b的值为TRUE, (..)返回TRUE,就不会继续计算c了,返回值就是b
如果b的值为FALSE,(..)返回FALSE; (..) or c返回值就是c
2.2            如果a为FALSE,(a and b)返回a的值,也就是FALSE,短路规则不计算b
(..) or c直接返回c


a and b or c <=> (a and b) or c
1        compute a and b,if a is true, return b,
1.1            if b is TRUE, whole (a and b) is TRUE, otherwise FLASE
2        compute (a and b) or c
2.1            if a is TRUE, whole (a and b) returns b, go on to compute b
if b is TRUE, (..) returns TRUE, it is not necessary to compute c. return b
if b is FALSE,(..) returnsFALSE; (..) or c returns c
2.2            if a is FALSE,(a and b) returns a, namely FALSE. It is not necessary to compute b
(..) or c returns c


通过分析可以看出,利用a and b or c 替代三目运算符有一个需要注意的地方,
就是b的逻辑值,必须为TRUE.如果b本身是零, None, 空list, tuple, dict或者空string,
还是必须继续使用if... else... 结构.

It's easy to find that: if you want to use a AND b OR c. as ternary operator, you must make sure that b is TRUE. If b is one of Zero, None, empty list, empty tuple, empty dict or empty string, you have to use
if .. else .. structure.

No comments :

Post a Comment