python中的三元运算

if...else...

python中的三元运算表达式为:true_part if condition else false_part

>>> 1 if True else 0  
1  
>>> 1 if False else 0  
0  
>>> "Fire" if True else "Water"  
'Fire'  
>>> "Fire" if False else "Water"  
'Water'

and...or...

还有一种是and...or...,利用条件判断的优先特性来实现三元条件判断,比如P∧Q,在Python中如果P为假,那么Python将不会继续执行Q,而直接判定整个表达式为假(P值),当然如果P为真,那就还要继续执行Q来决定整个表达式值;同样的P∨Q,如果P为真,那么就不会继续执行Q了…,其原型是condition and true_part or false_part.

>>> True and 1 or 0  
1  
>>> False and 1 or 0  
0  
>>> True and "Fire" or "Water"  
'Fire'  
>>> False and "Fire" or "Water"  
'Water' 

Python的三元表达式有如下几种书写方法:

if __name__ == '__main__':  
    a = ''  
    b = 'True'  
    c = 'False'  
      
    #方法一:为真时的结果 if 判定条件 else 为假时的结果  
    d = b if a else c  
    print('方法一输出结果:' + d)  
      
    #方法二:判定条件 and 为真时的结果 or 为假时的结果  
    d = a and b or c  
    print('方法二输出结果:' + d)  
      
    #以上两种方法方法等同于if ... else ...  
    if a:  
        d = b  
    else:  
        d = c  
    print('if语句的输出结果:' + d)  

输出结果:

方法一输出结果:False
方法二输出结果:False
if语句的输出结果:False

说明:

判断条件:a为空串,所以判断条件为假
当判断条件为真时的结果:d = b
当判断条件为假时的结果:d = c

原文地址:https://www.cnblogs.com/ccorz/p/sanmuyunsuan1.html