0

i would like to know if there is an adequate python alternative for my beloved C Makro 'Exp1 ? Exp2 : Exp3'.

I already tried to google but can't seem to find anything.

Example:

x = 0.5
(x > 0) ? 1 : 0



if(type == "release"):
        release = True
else:
        release = False
lukas
  • 1
  • 3
  • [https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator) may help – jia Jimmy Apr 01 '19 at 08:28

4 Answers4

2

It looks like this in your case

1 if x > 0 else 0
Ursus
  • 29,643
  • 3
  • 33
  • 50
0

For Python 3.x:

Ternary Operators:

trueExp if expr. else falseExp 

i.e:

x = 0.5
print(1 if x > 0 else 0)   # 1

For Python 2.5 and older versions:

Is there an equivalent of C’s ”?:” ternary operator?:

[expr.] and [trueExp] or [falseExp ]

i.e:

x = 0.5
print((x > 0) and 1 or 0)   # 1
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

What you are looking for is called a ternary operator.

There are multiple ways to achieve this in Python, but you will most often find this construct:

x = 0.5
print(1 if x > 0 else 0)
Callidior
  • 2,899
  • 2
  • 18
  • 28
0

Python does not have exactly something like Exp1 ? Exp2 : Exp3.

However, you can condense if-else statements into a single line. Something like

Exp2 if Exp1 else Exp3 would be somewhat Python equivalent of what you are looking for.

(I have followed the order in which you have written the C code)

More precisely, it is something like:

TrueVal if Expression else FalseVal.

Pranav Totla
  • 2,182
  • 2
  • 20
  • 28