Is There '?' Control Flow in Python?

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

是的,条件表达式在Python 2.5+中可用:

return n if n <= 1 else fibo(n-1) + fibo(n-2)

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.

链接地址: http://www.djcxy.com/p/7402.html

上一篇: 如何写python中的if和else

下一篇: 在那儿 '?' Python中的控制流?