Is There '?' Control Flow in Python? [duplicate]

久未见 提交于 2019-12-22 06:42:39

问题


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

回答1:


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

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



回答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.



来源:https://stackoverflow.com/questions/7778400/is-there-control-flow-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!