Home  >  Article  >  Backend Development  >  Share an example tutorial on the operation logic of and / or in python

Share an example tutorial on the operation logic of and / or in python

零下一度
零下一度Original
2017-05-26 11:58:442624browse

pythonThe core idea of ​​and and or operations——Short-circuit logic

Started to read recently Liao Xuefeng's python tutorial, I plan to put "learn python the hard way" first, because the last few chapters still feel a bit difficult (well, I'm too weak, but take your time, one step at a time), thinking about it After reading Liao Xuefeng's tutorial, go back and maybe you can get some ideas.

Okay, let’s get back to the point. The reason why I wrote this today is because the and / or operation appeared in the filter chapter of Liao Xuefeng’s tutorial. This was not mentioned in the previous tutorial. I was a little confused when I first read it. , I was 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, I checked some operational logic about and / or on the Internet, and added my own understanding, and summarized it as follows (I don’t know if it is wrong, if If there are any mistakes, please correct me):

1. Contains a logical operator

First, let’s start with the basic concepts. Which objects in Python will be treated as False? And which ones are True?

**In Python, None, 0 in any numeric type, empty string "", empty tuple (), empty list [], empty dictionary {} are treated as False, and If a custom type implements the nonzero () or len () method and the method returns 0 or False, its instance will also be treated as False, and other objects will be True. **

The following is the simplest logical operation:

    True  and True    ==> True                  True  or True    ==> True
    True  and False   ==> False                 True  or False   ==> True
    False and True    ==> False                 False or True    ==> True
    False and False   ==> 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] become 0 and 1 (False and True), so it is 0 (False).

example 2

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

If both are False at the same time, return the value on the left.

2. Contains two or more logical operators

Once there is more than one logical operator and / or, the core idea of ​​its operation rules is short-circuit logic. Okay, let’s take a look at short-circuit thinking (my own summary, which may be somewhat different from other people’s opinions on the Internet, please listen to my analysis slowly):

ExpressionFrom Left-to-right operation, if the logical value on the left side of or is True, all expressions after or will be short-circuited and the expression on the left side of or will be output directly.

Expressions are evaluated from left to right. If the logical value on the left side of and is False, all subsequent and expressions will be short-circuited until or appears, and the expression on the left side of and will be output. Go to the left side of or and participate in the next logical operation.

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

It may be a bit abstract, that’s okay, let’s give some examples next.

 Here is a clever method that allows us to intuitively understand the short-circuit situation when Python processes these logical statements (I also learned it from others)

Okay, let us start from the simple At the beginning, assume that it is all and statements 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'
    
    #显示结果如下
    A

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

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'

    #显示结果如下
    A
    B
    C

 The logical value of a() is True and cannot be short-circuited. Then, perform a logical operation with b() and return the logical value True of b(), which is the same as c() Perform logical operations and return the logical value False of c(). If all are followed by and statements, they are all short-circuited and the expression of c() is finally returned.

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'

    #显示结果如下
    A
    ok

 The logical value of a() is True, followed by or statements, all short-circuited, and finally the expression of a() is returned.

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'

    #显示结果如下
    A
    B
    C
    ok

 The logical value of a() is True and cannot be short-circuited. Then, perform a logical operation with b() and return the logical value False of b(), which is the same as c() Perform logical operations and return the logical value True of c(). If all are followed by or statements, then they are all short-circuited, and finally the expression of c() is returned.

Let’s talk about the situation when and and or statements coexist:

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 that it is difficult if the statement is very long , let's analyze it carefully. First, the logical value of a() is False, and then there are three and statements up to the or statement: a() and b() and c() and d(), all of which are short-circuited. Get a() or e() to be True, output e(), get e() and F() to be True, output f(), followed by the or statement, short-circuit everything after it. (With a good understanding of the three points of short-circuit logic I summarized, there should be no problem.)

3. ternary operationoperator

Before python2.5, python did not have a ternary operator. Guido Van Rossum believed that it did not help python become more concise. However, programmers who were accustomed to c, c++ and java programming tried to use and or or to simulate the ternary operator. operator, and this uses python's short-circuit logic.

 Ternary operation operator bool? a : b, if bool is true, then a, otherwise b.

  转化为 python 语言为:

        bool and a or b

  如何理解呢? 首先 a , b 都为真,这是默认的。如果 bool 为真, 则 bool and a 为真,输出 a ,短路 b 。如果 bool 为假,短路 a,直接 bool or b ,输出 b 。

  换一种更简单的写法:

       return a if bool else b

【相关推荐】

1. Python and、or以及and-or语法总结

2. 解析python中and与or用法

3. 详细介绍Python中and和or实际用法

4. 总结Python的逻辑运算符and

5. Python:逻辑判断与运算符实例

The above is the detailed content of Share an example tutorial on the operation logic of and / or in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn