


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!

ToappendelementstoaPythonlist,usetheappend()methodforsingleelements,extend()formultipleelements,andinsert()forspecificpositions.1)Useappend()foraddingoneelementattheend.2)Useextend()toaddmultipleelementsefficiently.3)Useinsert()toaddanelementataspeci

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

In the fields of finance, scientific research, medical care and AI, it is crucial to efficiently store and process numerical data. 1) In finance, using memory mapped files and NumPy libraries can significantly improve data processing speed. 2) In the field of scientific research, HDF5 files are optimized for data storage and retrieval. 3) In medical care, database optimization technologies such as indexing and partitioning improve data query performance. 4) In AI, data sharding and distributed training accelerate model training. System performance and scalability can be significantly improved by choosing the right tools and technologies and weighing trade-offs between storage and processing speeds.

Pythonarraysarecreatedusingthearraymodule,notbuilt-inlikelists.1)Importthearraymodule.2)Specifythetypecode,e.g.,'i'forintegers.3)Initializewithvalues.Arraysofferbettermemoryefficiencyforhomogeneousdatabutlessflexibilitythanlists.

In addition to the shebang line, there are many ways to specify a Python interpreter: 1. Use python commands directly from the command line; 2. Use batch files or shell scripts; 3. Use build tools such as Make or CMake; 4. Use task runners such as Invoke. Each method has its advantages and disadvantages, and it is important to choose the method that suits the needs of the project.

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
