115

do you know if Python supports some keyword or expression like in C++ to return values based on if condition, all in the same line (The C++ if expressed with the question mark ?)

// C++
value = ( a > 10 ? b : c )
Abruzzo Forte e Gentile
  • 13,745
  • 25
  • 90
  • 169
  • 4
    That C++ operator is called the "conditional operator" or the "ternary operator". –  Feb 03 '10 at 12:47

2 Answers2

188

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 isn't identical as the short circuiting effect is lost:

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

There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.

Mark Byers
  • 767,688
  • 176
  • 1,542
  • 1,434
1

simple is the best and works in every version.

if a>10: 
    value="b"
else: 
    value="c"
Tiago Martins Peres
  • 12,598
  • 15
  • 77
  • 116
ghostdog74
  • 307,646
  • 55
  • 250
  • 337