Introduction to the use of the ternary operator of Python language skills _python

Source: Internet
Author: User
Tags in python

Python does not support ternary operators in C + +? : The alternative is ... if ..... else ...
For example, use the following syntax to achieve a minimum value of three digits.
ND1 if nD1 < (nD2 if nd2<nd3 else nD3) Else (nD2 if nD2 < nD3 else nD3)

The correct method of the Python ternary operator

Because the next week to write the project in PHP, so the weekend at home to see the syntax of PHP, see ternary descriptor, suddenly remembered Python is no ternary descriptor, the impression vaguely remember to have the realization of the simulation, so on the internet search.
(corresponding to the C language X?) V1:V2)

One of them is:

(X and V1) or V2

Normally there will be no error, but the article also mentions that when v1= "", there will be problems
Like what

Copy Code code as follows:

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

The output will always be: V

The perfect solution is mentioned in the Python core programming:

V1 if X else V2

The original text reads as follows:

If you're from C + + or the Java world, it's hard to ignore the fact that Python is a very long
There are no conditional expressions in a period of time (C?) X:Y), or ternary operator. (C is a conditional expression; X is when C is True
As a result, Y is the result of C to False) Fan Rossam has been refusing to join such a function as he believes should be
Keeping the code simple makes it easy for programmers to make mistakes. But after more than 10 years, he gave up, mainly because people tried to use
And and or to simulate it, but most of them are wrong. According to the FAQ, the correct approach (not unique) is
(C and [X] or [Y]) [0]. The only problem is that the community disagrees with such a grammar. (You can take a look at PEP 308, whose
There are different scenarios.) People have expressed a great demand for this problem of Python.
At last, Fan Rossam chose one of the most favoured (and favourite) schemes, and then applied it to the standard library.
Some of the modules. According to PEP, "This review examines a large number of real-world cases, including different applications, and by different
The programmer completes the code. The syntax for the last Python 2.5 set is: X if C else Y.

As mentioned above, this syntax is added to the python2.5, but because it will not use 2.4 and previous versions, so it is enough ~

Most advanced languages now support "?" This ternary operator (ternary operator), which corresponds to the following expression: condition? Value if True:value if False. Oddly enough, such a common operator Python does not support! Admittedly, we can express it through if-else statements, but a line of code can be done in more than one line, obviously not concise enough. It doesn't matter, in Python there is actually a corresponding expression of the way.

For example: char *ret = (x!=0)? "True": "false" this line of code corresponds to the python form is ret = (x and "True") or "false" (very simple, in fact, parentheses can be removed). At run time, the Python virtual opportunity evaluated the Boolean expression to the right of the assignment (note that this is not a ternary expression), and the return value is the last parsed value. Why is "last parsed" instead of "last" in an expression? Because a Boolean expression has a short-circuit effect, such as a or B, if a is true then no analysis of B is made. Well, I guess we're pretty much in the clear now about how the Python code works. If x is true, because the string "true" is also true, then returns "true", whereas X is false, then it is not necessary to look at the string "true" (short-circuit effect) and return "False" directly.

It is easy to see that ternary operations in Python can actually be expressed by borrowing Boolean values. Then, sometimes there is a little problem. For instance, char *ret = x? "" or "VAL". According to the previous example, it's natural to think of this in Python, a ret = x and "" or "VAL". Wrong! Regardless of whether the Boolean value of X is True or FALSE, the RET is always "VAL". Is that weird? Not surprisingly, because the boolean evaluation of an empty string in Python is false, so that X and "" is always false, so the nature of the RET is always "VAL". There are two ways to solve this problem, the first, and one I like, is to write a ret = not X and "VAL" or "". Second, trouble a little ret=x and ["] or [VAL], and then fetch ret[0] as the return value, because ["] evaluates to True in Boolean value.

Discussion one: The first method code is obviously concise and efficient, so is it necessary to use the second kind? Of course, the first approach has limitations that can only be used if we are very clear that one of the value Boolean values cannot be false. In our example, because "VAL" definitely returns true, it can be used. If it is two variables, such as ret=x and Val1 or val2, you can just as honestly write ret=x and [val1] or [Val2], and then take ret[0] as a result. Because this line of statement is not expressed "when X returns VAL1 for true, otherwise returns VAL2", but "returns Val2" when X is True and Val1 returns VAL2 for true.

Discussion II: We all know that Python has lists and tuple, the preceding line of code ret=x and [""] or ["Val"] we are solving through the list, some people may prefer tuple, so we write Ret=x and ("") or ("Val"). Wrong! Here Ret[0] is always an empty string (tested on 2.5). This is the point I compare faint, why ["] is True and (") false?

Finally, we enclose the boolean evaluation result of Python for the typical numerical value, which is useful for us to write the equivalence statement of ternary operation.


0, ', None, [], (), {}, (") Td>
input boolean evaluation
1,-1,[' "] True
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.