


Share an example tutorial on the operation logic of and / or in python
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
【相关推荐】
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
