Boolean 'and' in Python

Can someone explain the reasoning of the following tests?

>>> 1 and True True >>> {'foo': 'Foo'} and True True >>> {} and True {} >>> 
+4
source share
2 answers

In the context of Boolean operations, and also when expressions are used by flow control operators, the following values ​​are interpreted as false: False, None, numeric zero of all types and empty strings and containers (including strings, tuples, lists, dictionaries, sets, and freezensets). All other values ​​are interpreted as true.

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is computed and the return value is returned.

An expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is computed and the return value is returned.

Read more about logical operations for more information: http://docs.python.org/reference/expressions.html#boolean-operations

+5
source

Python has no logical or logical or. Its and and or operators are combined , which means that they return the first invalid or true operand or second operand.

+8
source

All Articles