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

1

19

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.

Candlenut answered 15/6, 2010 at 13:40 Comment(1)
V
24

Try

 print ("paid: " + str(paid) + " €") if paid else "not paid"
Vergne answered 15/6, 2010 at 13:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.