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'

Updated on: 26-Feb-2020

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements