tutorial on sharing examples of and/or in Python

Source: Internet
Author: User
python The core idea of middle and and OR operation ——— short-circuit logic

Recently began to look at Liaoche's Python tutorial, intends to first put "learn Python the Hard way", because the last few chapters feel still a bit difficult (OK, I am too weak, but slowly, step by step), think of the Liao Xuefeng after the tutorial and then back to the head, Maybe some ideas.

Well, the reason why write this today, is because in the Liu Xuefeng tutorial in the filter chapter appeared in the and/or operation, the previous tutorial did not mention this, just look at the time some confusion, confused, the code is as follows:

    #把一个序列中的空字符串删掉    1>  def not_empty (s):    2>      return S and S.strip ()    3>    4>  Filter (Not_empty, [' A ', ' ', ' B ', None, ' C ', '  ])

Later on the Internet to check some of the operational logic of and/or, together with their own understanding, summed up as follows (I do not know whether it is wrong, if there are flaws, please treatise):

1. Include a logical operator

First, starting with the basic concept, which objects in Python will be treated as False? And which is True?

* * In Python, none, 0 in any numeric type, empty string "", Empty tuple (), empty list [], empty dictionary {} are treated as false, and custom types, if the nonzero () or len () method is implemented and the method returns 0 or FALSE, its instance is also treated as false, and the other objects are true. **

Here's the simplest logical operation:

    True and True    ==> true                  true  or True    ==> true    and  false   ==> false                 True  or False   ==> true    false and True    ==> false                 or True    ==> true    False and False   ==> false                 or false   ==> false

Using the above two points, we can give some examples:

Example 1

    >>> a = [0, 1, ' ', 3]    >>> a[0] and a[1]    0

A[0] = 0, a[1] = 1, so a[0] and a[1] becomes 0 and 1 (false and True), so 0 (false).

Example 2

    >>> a = [0, 1, ', 3]    >>> a[2] and a[1]    "

Both are False and return to the left value.

2. Contains two and more logical operators

Logical operator and/or once more than one, the core idea of its operational rules is short-circuit logic. OK, so let's get to know the short-circuit idea (I summed up, may be some other people on the Internet, and listen to my analysis):

The expression is left-to-right, and if the left logical value of OR is True, then all expressions that are short-circuited or are directly output or left-hand expressions.

The expression is left-to-right, and if the left logical value of and is False, then all the and expressions are shorted, until an or appears, and the output and left expression to the left of or is involved in the next logical operation.

If the left of the or is False, or if the left side of and is True, the short-circuit logic cannot be used.

Maybe a little abstract, that's okay, let's take a few examples next.

Here's an ingenious way to get a visual understanding of the short-circuiting of Python when it comes to handling these logical statements (I'm learning from others too)

Well, let's start with a simple one, assuming it's all an and statement or all or statements:

Example 1

    1>  def A ():    2>      print ' A '    3>      return []    4>  def b ():    5>      print ' B '    6>      return []    7>  def c ():    8>      print ' C '    9>      return 1    10> Def d ():    11>     print ' d '    12>     return []    13> def e ():    14>     print ' e '    15>     return 1    16>    17> If A () and B () and C () and D () and E ():    18>     print ' OK '        #显示结 Fruit as follows    A

The logical value of a () is False, followed by an and statement, all short-circuited, and finally the expression of a () is returned.

Example 2

    1>  def A ():    2>      print ' A '    3>      return 1    4>  def b ():    5>      print ' B '    6>      return 1    7>  def c ():    8>      print ' C '    9>      return []    10> Def d ():    11>     print ' d '    12>     return []    13> def e ():    14>     print ' e '    15>     return 1    16>    17> If A () and B () and C () and D () and E ():    18>     print ' OK '    #显示结 as follows    A    B    C

The logical value of a () is true, cannot be shorted thereafter, logical operation with B (), returns the logical value of B () True, logical operation with C (), returns the logical value of C () False, followed by the and statement, then all short, and finally returns the expression C ().

Example 3

    1>  def A ():    2>      print ' A '    3>      return 1    4>  def b ():    5>      print ' B '    6>      return []    7>  def c ():    8>      print ' C '    9>      return 1    10> Def d ():    11>     print ' d '    12>     return []    13> def e ():    14>     print ' e '    15>     return 1    16>    17> if a () or B () or C () or D () or E ():    18>     print ' OK '    #显示结果如下 C33/>a    OK

The logical value of a () is True, followed by an OR statement, all short-circuited, and finally an expression of a ().

Example 4

    1>  def A ():    2>      print ' A '    3>      return []    4>  def b ():    5>      print ' B '    6>      return []    7>  def c ():    8>      print ' C '    9>      return 1    10> Def d ():    11>     print ' d '    12>     return []    13> def e ():    14>     print ' e '    15>     return 1    16>    17> if a () or B () or C () or D () or E ():    18>     print ' OK '    #显示结果如下 C33/>a    B    C    OK

The logical value of a () is true, cannot be shorted thereafter, logical operation with B (), returns the logical value of B () False, logical operation with C (), returns the logical value of C () True, followed by an or statement, then all short, and finally returns the expression C ().

Let's take a look at the same situation where the and and OR statements exist:

Example 5

    1>  def A ():    2>      print ' A '    3>      return []    4>  def b ():    5>      print ' B '    6>      return []    7>  def c ():    8>      print ' C '    9>      return 1    10> Def d ():    11>     print ' d '    12>     return []    13> def e ():    14>     print ' e '    15>     return 1    16> def f ():    17>     print ' F '    18>     return 1    19> def g ():    20>     print ' G '    21>     return []    22> def h ():    23>     print ' h '    24>     return 1    25>    26> If A () and B () and  C () and D () or E () and f () or g () and H ():    27>
  
   print ' OK '    #输出结果如下:    A    E    F    OK
  

Don't think the statement is very long it is difficult to analyze, first of all, the logical value of a () is False, followed by the or statement there are three and statements: a () and B () and C () and D (), are short-circuited. Get a () or E () to True, the output e (), the E () and F () is true, the output F (), followed by an or statement, then the short circuit after all. (combined with my summary of the short circuit logic of three points to understand well, should be no problem.) )

3. Ternary operator

Before python2.5, Python had no ternary operator, Guido Van Rossum thought it would not help python to be more concise, but programmers who used C, C + + and Java programming tried to simulate ternary operations with and OR OR. Using Python's short-circuit logic.

Ternary operator bool? A:B, if BOOL is true, a, otherwise B.

Translate to Python language as:

bool and A or B

How to understand it? First A, B are true, this is the default. If BOOL is true, then bool and a are true, output a, short-circuit B. If bool is false, short circuit a, direct bool or B, output B.

In a simpler way:

Return a if bool else b

"Recommended"

1. Python and, or, and and-or syntax summary

2. Parsing and and or usage in Python

3. Detailed description of and and or actual usage in Python

4. Summarize Python's logical operators and

5. Python: Logical judgment and Operator instance

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.