Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python boolean truth tests [duplicate]

Tags:

python

boolean

Possible Duplicate:
Python Ternary Operator

Does Python have an equivalent of the ternary operator?:

( x < 5 ? 1 : 0 )

Or must I express the same thing with an if-else pair?

like image 848
SK9 Avatar asked Dec 12 '22 12:12

SK9


2 Answers

You can use a conditional expression:

1 if x < 5 else 0

In code written for very old versions of Python, you may also see:

x < 5 and 1 or 0

However, the conditional expression form is preferred for Python 2.5 and later.

like image 183
Greg Hewgill Avatar answered Jan 10 '23 20:01

Greg Hewgill


Python has:

1 if x < 5 else 0

or the old style:

x < 5 and 1 or 0
like image 37
bradley.ayers Avatar answered Jan 10 '23 20:01

bradley.ayers