Python implementation question-mark expression (?) The method

Source: Internet
Author: User
And and or in Python are quite different from other languages
And and or in other languages are the result of returning a bool type, not python. It returns one of the values that do the and and or operations.
The value that determines the value of the expression returns that value.

Copy the Code code as follows:


>> 5 and ' '

The result here is ', an empty string, because it causes the expression to be false.
That is, in and, only the previous value is false, it is possible to become a result. Otherwise, the result is the value that follows.

Knowing the process of and and or running, you can implement the expression:
Copy the Code code as follows:


if (expression):
Return TrueValue
Else
Return Falsevalue

And this equivalent notation is (similar to the expression):
Copy the Code code as follows:


expression and TrueValue or Falsevalue
#或者
(Expression and (TrueValue,) or (Falsevalue,)) [0] #感谢snake117提供的建议

#这种是避免truevalue有可能是false的情况, such as an empty string

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