syntax – Conditional operator in Python?
syntax – Conditional operator in Python?
From Python 2.5 onwards you can do:
value = b if a > 10 else c
Previously you would have to do something like the following, although the semantics isnt identical as the short circuiting effect is lost:
value = [c, b][a > 10]
Theres also another hack using and … or but its best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I wont even write the hack here as I think its best not to use it, but you can read about it on Wikipedia if you want.
simple is the best and works in every version.
if a>10:
value=b
else:
value=c