4

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?

Community
  • 1
  • 1
Ken
  • 30,811
  • 34
  • 116
  • 155

2 Answers2

12

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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
1

Python has:

1 if x < 5 else 0

or the old style:

x < 5 and 1 or 0
bradley.ayers
  • 37,165
  • 14
  • 93
  • 99