Python and-or, pythonand-or

Source: Internet
Author: User

Python and-or, pythonand-or

[Original] The and-or in python is often used to implement the ternary operators like C :? ,

The statement is xxx and xxx or xxx, so that multiple expressions can be implemented in one line.

Code:

(1) def Judge ():

If a> 10:

Return "big"

Elif a> 5:

Return "middle"

Else:

Return "small"

(2) def judge (B ):

Return B> 10 and "big" or B> 5 and "middle" or "small"

(1) and (2) achieve the same effect.

 

However, it should be noted that and-or is not fully equivalent to the ternary operator, because a and B or c,

If B is a false value, c will be returned (the computer is relatively lazy --!)

 

However, there are skills to achieve this:

Def choose (bool, a, B ):

Return (bool and [a] or [B]) [0]

If bool is true, [a] is returned. Otherwise, [B] is returned. As mentioned above, the computer is very lazy.

Determine whether the value before and is true. If it is true, then xxx and xxx are true.

 

[0] at the end of return is used to output results in numbers rather than in lists: Add [0] 7 without [0] [7]

Example: choose (True, 0, 6)

>>> 0

Choose (True, 7, 6)

>>> 7

Choose (False, 0, 6)

>>> 6

Choose (False, 7, 6)

>>> 6

If [0] is not added,

Choose (True, 0, 6)

>>> [0]

 

That's all.

I use python QAQ

Come on !!!

 

Reference: http://python.jobbole.com/81233/


   

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.