Python - if/else Ternary Expression

Introduction

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

if X: 
    A = Y 
else: 
    A = Z 

Python can write the above statement as follow:

A = Y if X else Z 

Demo

A = 't' if 'test' else 'f'      # For strings, nonempty means true 
print( A )
A = 't' if '' else 'f' 
print( A )# from   ww  w .j  a  va2  s. co m

Result

The following statement

A = ((X and Y) or Z) 

is equivalent to the ternary form:

A = Y if X else Z 

Related Topic