Introduction to the use of ternary operators in Python

Source: Internet
Author: User
Currently, most advanced languages support "?". The ternaryoperator corresponds to the following expression: condition? Valueiftrue: valueiffalse. It is strange that such a common operator python does not support python and does not support ternary operators in C/C ++? :, The alternative method is... if... else...
For example, the following syntax is used to calculate the minimum value of three numbers.
ND1 if nD1 <(nD2 if nD2

The correct method for python ternary operators

Because I will use php to write projects next week, I will re-read the php syntax at home on weekends. when I saw the ternary descriptor, I suddenly remembered that python did not have the ternary descriptor. I vaguely remember that there was a simulated implementation, so I searched the internet.
(Corresponding to the C language X? V1: V2)

One of them is:

(X and V1) or V2

Under normal circumstances, there will be no errors, but as mentioned in the article, when V1 = "", there will be problems
For example

The code is as follows:


Print (True and '') or 'V'
Print (False and '') or 'V'

Always output: V

The perfect solution is mentioned in core python programming:

V1 if X else V2

The original article is as follows:

If you are from the C/C ++ or Java world, it is hard to ignore the fact that Python is on a very long
There is no conditional expression (C? X: Y), or ternary operator. (C is a conditional expression; X is True when C is True.
The result when C is False.) you have been refused to add such a function because he thinks
This keeps the code simple and prevents programmers from making mistakes easily. but after more than a decade, he gave up, mainly because people tried to use
And or to simulate it, but most of them are incorrect. according to the FAQ, the correct method (not the only one) is
(C and [X] or [Y]) [0]. The only problem is that the community does not agree with this syntax. (you can take a look at PEP 308.
There are different solutions.) for Python, people have expressed great demands.
Guido van Rosam finally chose the most favored (and also his favorite) solution and applied it to the standard library.
According to PEP, "This review examines a large number of real-world cases, including different applications and
Code completed by the programmer. "Finally, the syntax for Python 2.5 integration is determined to be: X if C else Y.

As mentioned above, this syntax is added in python2.5, but it is enough because 2.4 and earlier versions are not used at ordinary times ~

Currently, most advanced languages support "?". The ternary operator corresponds to the following expression: condition? Value if true: value if false. It is strange that such a common operator is not supported by python! It is true that we can express it through the if-else statement, but it is not concise enough that a line of code can complete multiple lines. It doesn't matter. there are actually corresponding expressions in python.

For example, char * ret = (x! = 0 )? "True": "False" the python format corresponding to this line of code is ret = (x and "True") or "False" (very simple, in fact, parentheses can be removed ). During runtime, the python virtual opportunity evaluates the Boolean expression on the right of the value assignment operator (note that this is not a ternary expression), and the return value is the last value analyzed. Why is "last analyzed" instead of "last" in the expression? Because a Boolean expression has a short circuit effect, such as a or B, if a is true, B will not be analyzed. Well, now we almost understand the principles of this line of python code. If x is True, because the string "True" is also True, "True" is returned. otherwise, x is false, so there is no need to check the string "True" (short-circuit effect ), directly return "False ".

It is not hard to see that ternary operations can actually be expressed by using Boolean values in python. Then, there may be some minor issues. For example, char * ret = x? "" Or "VAL ". Based on the previous example, we naturally think that we should write this in python, ret = x and "" or "VAL ". Wrong! No matter whether the boolean value of x is true or false, ret always gets "VAL ". Strange? It is not surprising that the Boolean value of an empty string in python is false, so that x and "" are always false, so ret always gets "VAL. There are two ways to solve this problem. The first one is my favorite one, that is, writing ret = not x and "VAL" or "". Second, please try ret = x and [""] or ["VAL"] and use ret [0] as the return value each time, this is because the value of [""] in Boolean is true.

Discussion 1: the code in the first method must be concise and efficient. is it necessary to use the second method? Of course, the first method has limitations. it can be used only when one of the values is clearly Boolean and cannot be false. In our example, because "VAL" definitely returns true, it can be used. If there are two variables, like ret = x and val1 or val2, you can only honestly write ret = x and [val1] or [val2], then, ret [0] is taken as the result. This statement does not indicate "val1 is returned if x is true, val2 is returned otherwise", but "val2 is returned if x is true and val1 is true; otherwise, val2 is returned ".

Discussion 2: We all know that python contains list and tuple. The previous code ret = x and [""] or ["VAL"] is solved through list, some may prefer tuple, so they write ret = x and ("") or ("VAL "). Wrong! Ret [0] is always a null string (tested on 2.5 ). Why [""] is true and ("") is false?

Finally, we attached the boolean result of python for a typical value, which is very useful for writing equivalent statements of ternary computation.


Input Boolean
1,-1,[""] True
0, "", None, [], (), {}, ("") False

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.