Question-Mark expression in Python

Source: Internet
Author: User

we know that a question mark expression exists in the C statement, such as the following:

A=2>1? 10:-10;

So are there similar question-mark expressions in the Python scripting language? The answer is yes. And there are two ways of doing it.

Method 1: Use the If Else implementation

The following example:

b = 5

A = 2 if b = = 4 Else 1

Print a

Method 2: Implement using logical operators

The following example:

b = 5

A = b = = 4 and 2 or 1

Note: Use logical operations to ensure that the variable value after and cannot be non-otherwise an error occurs.

Tips

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. Take a look at the following example:

>> 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 above expression.

This article is from the "Green Peak" blog, please make sure to keep this source http://zhuxianzhong.blog.51cto.com/157061/1613851

Question-Mark expression in Python

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.