Computer >> Computer tutorials >  >> Programming >> Python

Does Python have a ternary conditional operator?


Ternary operator was added in Python 2.5. Its syntax is:

Syntax

x if expr==True else y

Example

Following example illustrates usage

>>> percent=59
>>> 'pass' if percent>=50 else 'fail'
'pass'
>>> percent=45
>>> 'pass' if percent>=50 else 'fail'
'fail'