Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operator in Python? [duplicate]

Tags:

python

syntax

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 ) 
like image 297
Abruzzo Forte e Gentile Avatar asked Feb 03 '10 12:02

Abruzzo Forte e Gentile


People also ask

What is ?: In Python?

Ternary operators are also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5. It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

Is there a conditional operator in Python?

Python supports one additional decision-making entity called a conditional expression. (It is also referred to as a conditional operator or ternary operator in various places in the Python documentation.) Conditional expressions were proposed for addition to the language in PEP 308 and green-lighted by Guido in 2005.

How do you write a conditional operator in Python?

In Python, conditional expression is written as follows. The condition is evaluated first. If condition is True , X is evaluated and its value is returned, and if condition is False , Y is evaluated and its value is returned. If you want to switch the value by the condition, simply describe each value as it is.

What is the difference between IS and == in Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory.


1 Answers

From Python 2.5 onwards you can do:

value = b if a > 10 else c 

Previously 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.

like image 188
Mark Byers Avatar answered Oct 05 '22 01:10

Mark Byers