In Python? : Introduction to the use of three-dimensional expressions _python

Source: Internet
Author: User
Tags php code in python

(1) variable = A If exper else b
(2) variable = (Exper and [b] or [C]) [0]
(2) variable = exper and B or C

The above three uses all can achieve the goal, like C language variable = exper? B:C: If the value of the Exper expression is true then variable = b, otherwise variable = c

For example:

Copy Code code as follows:

a,b=1,2
Max = (A If a > b else b)
Max = (A > B and [a] or [b]) [0] #list
Max = (A > B and a or b)


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.

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

python three-dimensional expression

Previously learned Python mentions the ternary conditional expression condition similar to C language? True_part:false_part, although Python does not have a three-mesh operator (?:), there is a similar alternative, that is, true_part if condition else false_part.

Copy Code code as follows:

>>> 1 if True else 0
1
>>> 1 if False else 0
0
>>> "Fire" if True else "Water"
' Fire '
>>> "Fire" if False else "Water"
' Water '

I've been using it all the time in programming, until one day I found an interesting trick, that is, and-or skills, using the priority characteristics of conditional judgments to make ternary conditional judgments, such as p∧q, in Python if P is false, then Python will not continue to execute Q, and directly determine the entire expression is False (P value), of course, if P is true, then continue to execute Q to determine the entire expression value; the same p∨q, if P is true, then the Q will not continue ...

In fact, a lot of programming languages in the logic of the application of this mechanism, at present, I contact the seemingly vb/vbscript may not do so. With this mechanism in addition to improving efficiency in if judgments, we can explore some additional interesting features, such as the following PHP code:

Copy Code code as follows:

$conn = @mysql_connect (...) or Die ("Failed")

If Mysql_connect succeeds, it returns the resource resource handle, returns False if it fails, and so on, followed by an OR, which fails to execute the die statement after or, and then prints out the error message and terminates execution of subsequent code.

Again, like the following JavaScript code:

Copy Code code as follows:

function GetEvent (e) {
E = e | | window.event;
return e;
}

This code gets an event if the getevent is not passed the value (that is, E is undefined), or E is null (both represent false in JavaScript conditions), E = e | | The window.event expression will assign the window.event to E, otherwise the E is object, and the original expression will degenerate to E = e assignment, which means nothing changed.

Well, pulled so much, a little bit off, the following continue to talk about Python's and-or skills, so to speak, this technique is also the use of the specificity of the logic of judgment, seemingly in the real ternary expression if else does not come out when it has been playing the role of three-dimensional expression, Its prototype is condition and True_part or False_part, here are a few examples:

Copy Code code as follows:

>>> True and 1 or 0
1
>>> False and 1 or 0
0
>>> True and "Fire" or "Water"
' Fire '
>>> False and "Fire" or "Water"
' Water '

But it's worth noting that while the surface appears to work properly, there are also hidden risks lurking, and if our True_part itself is a value that Python has identified as false, this technique is not available, and we know that this is the case with an empty string.

Copy Code code as follows:

>>> True and "" or "Water"
' Water '

The above expression actually we expect to return to the null string, how to solve it, I found the solution in dive into Python: that is taking advantage of the list attribute, because the list containing the empty string has an expression value that is still true, so we can wrap it in the list first, And then after the expression is judged, the package is solved:

Copy Code code as follows:

>>> a = ""
>>> B = "Water"
>>> (True and [a] or [b]) [0]
''

Of course, to avoid errors, we can wrap them as functions:

Copy Code code as follows:

def iif (condition, True_part, False_part):
return (condition and [True_part] or [False_part]) [0]

Now Python has added the three-dimensional conditional expression support to the language feature, that is the first introduction of the article if else to write, so for the sake of good, for the ternary judgment or with the new if Else feature, in fact, Python official to add ternary expression syntax is also discussed for a long time, can refer to "PEP 308-conditional Expressions".

Related Article

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.