Table of Contents
1. Contains a logical operator
example 5
2. Contains two or more logical operators
ternary operationoperator" >3. ternary operationoperator
Home Backend Development Python Tutorial 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

May 26, 2017 am 11:58 AM

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

2

3

4

5

6

#把一个序列中的空字符串删掉

 

1>  def not_empty(s):

2>      return s and s.strip()

3>

4>  filter(not_empty, ['A', '', 'B', None, 'C', '  '])

Copy after login

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:

1

2

3

4

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

Copy after login

Using the above two points we can give some examples:

example 1

1

2

3

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

>>> a[0] and a[1]

0

Copy after login

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

1

2

3

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

>>> a[2] and a[1]

''

Copy after login

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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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

Copy after login

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

example 2

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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

Copy after login

 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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

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

Copy after login

 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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

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

Copy after login

 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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

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

Copy after login

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 语言为:

1

bool and a or b

Copy after login

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

  换一种更简单的写法:

1

return a if bool else b

Copy after login

【相关推荐】

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 of this Website
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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the advantages and disadvantages of templating? What are the advantages and disadvantages of templating? May 08, 2024 pm 03:51 PM

What are the advantages and disadvantages of templating?

How to download deepseek Xiaomi How to download deepseek Xiaomi Feb 19, 2025 pm 05:27 PM

How to download deepseek Xiaomi

Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Jul 01, 2024 am 07:22 AM

Google AI announces Gemini 1.5 Pro and Gemma 2 for developers

For only $250, Hugging Face's technical director teaches you how to fine-tune Llama 3 step by step For only $250, Hugging Face's technical director teaches you how to fine-tune Llama 3 step by step May 06, 2024 pm 03:52 PM

For only $250, Hugging Face's technical director teaches you how to fine-tune Llama 3 step by step

Share several .NET open source AI and LLM related project frameworks Share several .NET open source AI and LLM related project frameworks May 06, 2024 pm 04:43 PM

Share several .NET open source AI and LLM related project frameworks

A complete guide to golang function debugging and analysis A complete guide to golang function debugging and analysis May 06, 2024 pm 02:00 PM

A complete guide to golang function debugging and analysis

How do you ask him deepseek How do you ask him deepseek Feb 19, 2025 pm 04:42 PM

How do you ask him deepseek

How to save the evaluate function How to save the evaluate function May 07, 2024 am 01:09 AM

How to save the evaluate function

See all articles