Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 293
clwen Avatar asked Oct 15 '11 14:10

clwen


People also ask

Which Python keywords are conditional control flow statements select two?

A statement that controls the flow of execution depending on some condition. In Python the keywords if , elif , and else are used for conditional statements.

Is not in in Python?

Python “not in” operator It also checks the presence of a specified value inside a given sequence but it's return values are totally opposite to that of the in operator. When used in a condition with the specified value present inside the sequence, the statement returns False . Whereas when it is not, we get a True .


2 Answers

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

return n if n <= 1 else fibo(n-1) + fibo(n-2)
like image 70
phihag Avatar answered Oct 01 '22 14:10

phihag


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.

like image 22
Narendra Yadala Avatar answered Oct 01 '22 14:10

Narendra Yadala