Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: iif or (x ? a : b) [duplicate]

Possible Duplicate:
Python Ternary Operator

If Python would support the (x ? a : b) syntax from C/C++, I would write:

print paid ? ("paid: " + str(paid) + " €") : "not paid"

I really don't want to have an if-check and two independent prints here (because that is only an example above, in my code, it looks much more complicated and would really be stupid to have almost the same code twice).

However, Python does not support this operator or any similar operator (afaik). What is the easiest/cleanest/most common way to do this?

I have searched a bit and seen someone defining an iif(cond,iftrue,iffalse) function, inspired from Visual Basic. I wondered if I really have to add that code and if/why there is no such basic function in the standard library.

like image 340
Albert Avatar asked Jun 15 '10 13:06

Albert


1 Answers

Try

 print ("paid: " + str(paid) + " €") if paid else "not paid"
like image 146
Juri Robl Avatar answered Oct 21 '22 07:10

Juri Robl