Python - if/else Ternary Expression


Consider the following statement, which sets A to either Y or Z, based on the truth value of X:

if X: 
    A = Y 
    A = Z 

Python can write the above statement as follow:

A = Y if X else Z 


A = 't' if 'test' else 'f'      # For strings, nonempty means true 
print( A )
A = 't' if '' else 'f' 
print( A )#  ww w  .ja va  2 s .  co m


The following statement

A = ((X and Y) or Z) 

is equivalent to the ternary form:

A = Y if X else Z 

Related Topic