In python? : Introduction to the use of ternary expressions

Source: Internet
Author: User

(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 methods can achieve the goal, similar to the C language variable = exper? B: c; that is, if the value of the exper expression is true, variable = B; otherwise, variable = c

For example:

Copy codeThe Code is 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)


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

Python ternary expressions

The Python mentioned previously mentioned the conditional condition expression for C language-like expressions? True_part: false_part, although Python does not have a three-object operator (? :), But there are similar alternatives, that is, true_part if condition else false_part.

Copy codeThe Code is 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 used it all the time in programming. I found an interesting technique one day, that is, the and-or technique, which uses the priority feature of conditional judgment to implement Trielement conditional judgment, for example, if P is false in Python, Python will not continue to execute Q, but directly determine that the entire expression is false (P value). Of course, if P is true, then we need to continue executing Q to determine the value of the entire expression. For the same P semi Q, if P is true, we will not continue executing Q...

In fact, many programming languages have applied this mechanism in logic judgment. Currently, I have come to know that VB/VBScript may not do this. With this mechanism, in addition to improving the efficiency of if judgment, we can also explore some interesting functions, such as the following PHP code:

Copy codeThe Code is as follows:
$ Conn = @ mysql_connect (...) or die ("Failed ")

If mysql_connect is successful, the resource handle will be returned, and if it fails, False will be returned, and so on. There will be an or, that is, if the statement fails, the die statement after or is executed again. Therefore, the error message is output and subsequent code execution is terminated.

The following JavaScript code is used:

Copy codeThe Code is as follows:
Function getEvent (e ){
E = e | window. event;
Return e;
}

This code obtains the event. If no value is input to getEvent (that is, e is undefined), or e is NULL (both represent False in JavaScript conditions ), e = e | window. the event expression will set window. event is assigned to e. Otherwise, e is the Object, and the original expression is normalized to e = e, that is, no change is made.

Well, I 've got so many questions. I'll continue to talk about the and-or technique of Python. You can say that this technique also utilizes the particularity of logical judgment, it seems that when the true ternary expression if else does not come out, it has been playing the role of the ternary expression. Its prototype is condition and true_part or false_part. The following are several examples:

Copy codeThe Code is 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'

However, it is worth noting that although it seems to work normally, there are still unknown risks. If our true_part itself is a value recognized as False by Python, this technique is not available. We know that this is the case for empty strings.

Copy codeThe Code is as follows:
>>> True and "" or "Water"
'Water'

The above expression actually expects to return an empty string. How can this problem be solved? I found a solution in Dive Into Python: that is, using the list feature, because the expression value of the list containing null strings is still True, we can use the list to wrap it first, and then unpack it after the expression is determined:

Copy codeThe Code is as follows:
>>> A = ""
>>> B = "Water"
>>> (True and [a] or [B]) [0]
''

To avoid errors, we can encapsulate them as functions:

Copy codeThe Code is as follows:
Def iif (condition, true_part, false_part ):
Return (condition and [true_part] or [false_part]) [0]

Now Python has added support for ternary conditional expressions in the language features, that is, the if else writing method introduced at the beginning of this article, so for the sake of safety, the new if else feature is used for determining the ternary expression. In fact, Python has been discussing the syntax of adding the ternary expression for a long time. For details, refer to PEP 308-Conditional Expressions.

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.