Conditional operator in Python?

Do you know if Python supports any keyword or expression, as in C ++, to return values ​​based on an if condition, all on one line (C ++ if , expressed with a question mark ? )

 // C++ value = ( a > 10 ? b : c ) 
+60
python syntax
Feb 03 '10 at
source share
2 answers

Starting with Python 2.5, you can:

 value = b if a > 10 else c 

Previously, you had to do something like the following, although the semantics are not identical, because the effect of a short circuit is lost:

 value = [c, b][a > 10] 

There is also another hack using "and ... or", but it is better not to use it, because it has undesirable behavior in some situations, which can lead to difficult detection of an error. I won’t even write a hack because I think it’s better not to use it, but you can read about it on Wikipedia if you want.

+104
Feb 03 '10 at
source share

simple is the best and works in every version.

  if a>10: value="b" else: value="c" 
-2
Feb 03 2018-10-03T00
source share



All Articles