6

Possible Duplicate:
Python Ternary Operator

Is there control flow operator similar to '?' of C/C++ in python?

If there is a chunk of code similar to this:

return n <= 1 ? n : fibo(n-1) + fibo(n-2)

Will got an error like this:

File "fibonacci.py", line 2
    return n <= 1 ? n : fibo(n-1) + fibo(n-2)
                  ^
SyntaxError: invalid syntax
Community
  • 1
  • 1
clwen
  • 16,956
  • 27
  • 70
  • 91
  • 5
    It may be called that incorrectly; It takes three operands and so it is ternary in the same way that addition is binary. It happens that there arent many ternary operators in python or other algol descendands. This is uniquely identified as in phihag's answer as a "Conditional Expression" – SingleNegationElimination Oct 15 '11 at 14:34

2 Answers2

12

Yes, the conditional expression is available in Python 2.5+:

return n if n <= 1 else fibo(n-1) + fibo(n-2)
phihag
  • 245,801
  • 63
  • 407
  • 443
5

You can try this short circuit expression return n > 1 and fibo(n-1) + fibo(n-2) or n. While this is not the ternary statement, it is concise and does the job in this scenario.

Narendra Yadala
  • 9,110
  • 1
  • 24
  • 43