And and or in Python are logical operators in Python. How are their usages?
and:
In Python, and and or perform Boolean logic calculations as you would expect, but they do not return a Boolean value; instead, they return one of the values they are actually comparing.
code show as below:
' a' and 'b''b''' and 'b''''a' and 'b' and 'c''c'
In the Boolean context, the value of the expression is calculated from left to right. If all values in the Boolean context are true, then and returns the last value.
If a value in the boolean context is false, and returns the first false value
or:
code show as below:
' a' or 'b''a''' or 'b''b''' or [] or {}{}0 or 'a' or 'c''a'
When using or, the value is calculated from left to right in a Boolean context, just like and. If a value is true, or returns that value immediately
If all the values are false, or returns the last false value
Note that or in a boolean context will continue to perform expression calculations until the first true value is found, and then the remaining comparison values will be ignored
and-or:
and-or combines the previous two grammars, just inference.
a='first'
b='second'1 and a or b 'first'(1 and a) or b 'first'0 and a or b 'second'(0 and a) or b 'second'
This syntax looks similar to the bool? A: b expression in C language. The whole expression is calculated from left to right, so the calculation of the and expression is performed first. The calculation value of 1 and'first' is'first', and then the calculation value of'first' or'second' is'first'.
0 and'first' is calculated as False, and then 0 or'second' is calculated as'second'.
and-or is mainly used to imitate the ternary operator bool?a:b, that is, when the expression bool is true, take a, otherwise take b.
The and-or technique, bool and a or b expression, when the value of a in a Boolean context is false, it will not work like the C language expression bool? a: b.
Use and-or safely
code show as below:
a=""
b="second"(1 and [a] or [b])[''](1 and [a] or [b])[0]''
Since [a] is a non-empty list, it will never be false. Even if a is 0 or "or other false values, the list [a] is true because it has one element.
A responsible programmer should encapsulate the and-or technique into a function:
code show as below:
def choose(bool,a,b):return(bool and [a] or [b])[0]
print choose(1,'','second')
#''
Example supplement:
a ='first'
b ='second'
1 and a or b #Equivalent to bool=When true
' first'
0 and a or b #Equivalent to bool=When false
' second'
a =''
1 and a or b #When a is false, there is a problem
' second'(1and[a]or[b])[0]#Safe usage because[a]Impossible to be false, at least one element
''
So far, this article on how to use and and or in Python is introduced. For more related usage examples of and and or in Python, please search ZaLou.Cn
Recommended Posts