Python ternary operator details

Source: Internet
Author: User
Python does not have a ternary descriptor, but it can be implemented by simulation.
One of these is:

(X and V1) or V2

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

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

The output is always: V

The perfect solution is mentioned in Python core programming:

V1 if X else V2

The original text reads as follows:

If you're from a C + + or a Java world, it's hard to ignore the fact that Python is a long
There is no conditional expression in a period of time (C? X:Y), or ternary operator. (C is the conditional expression; X is when C is true
result, Y is the result when C is False) Fan Rossam has been refusing to join such a feature because he believes that it should be
Keeping the code simple makes it easy for programmers to make mistakes. But after more than 10 years, he gave up, mostly because people tried to use
And and or to emulate it, but most of them are wrong. 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 such a grammar. (You can take a look at PEP 308, which
There are different scenarios in the.) There is a great demand for Python's question.
The Fan Rossam finally chose the one that was most favored (and his favorite) and 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 code that the programmer completes. "The final syntax for Python 2.5 is determined as: X if C else Y.

As mentioned above, this grammar is added in python2.5, but because it will not be used in the 2.4 and the previous version, so it is enough ~

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