119

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
  • 14,423
  • 28
  • 99
  • 173
  • 5
    That C++ operator is called the "conditional operator" or the "ternary operator". –  Feb 03 '10 at 12:47

2 Answers2

200
value = b if a > 10 else c

For Python 2.4 and lower 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.

Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 7
    I've always wondered what notation they rejected as "too confusing" in favour of this. –  Feb 03 '10 at 12:47
  • 2
    +1, You can use this kind of 'if' even with lambda expressions! – Serge Feb 03 '10 at 13:16
  • 2
    @Neil, not sure if you're referring to the syntax ultimately chosen, or who said "too confusing", but the PEP summarizes all the rejected alternatives among other info: http://www.python.org/dev/peps/pep-0308/ – Peter Hansen Feb 04 '10 at 02:14
  • 11
    They should have used `test ? a : b`. The reasons cited for its rejection are weak. – Evgeni Sergeev Apr 04 '13 at 00:38
  • +! for Not sharing with us the 'not recomended' way ;) – Mercury Sep 27 '16 at 12:34
0

simple is the best and works in every version.

if a>10: 
    value="b"
else: 
    value="c"
Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
ghostdog74
  • 327,991
  • 56
  • 259
  • 343