|
In Python, logical operations can be carried out by and, or, and not, here's a look briefly and and or.
Logic and -and
For operation and contains an expression, Python interpreter will scan from left to right, returns a false value of the expression, no false value is the value of the last expression is returned.
Let's look at a use and examples:
# If all the expressions are true, return the last expression
print { "name": "Will"} and "hello" and 1
# Return the first false expression
print { "name": "Will"} and "" and 1
print { "name": "Will"} and [] and 1
print {} and [] and None
print { "name": "Will"} and [1] and None
-or Logical or
For an expression containing or operations, Python interpreter will scan from left to right, returns a true value of the expression, no true value is the value of the last expression is returned.
Look at the following examples:
# If all the expressions are false, return the last expression
print {} or [] or None
# Return the first true expression
print { "name": "Will"} or "hello" or 1
print {} or [1] or 1
print {} or [] or "hello"
Ternary operator
Many languages are supported ternary operator "bool a:? B", although not supported in Python ternary operator, but you can achieve the same effect by and-or.
expression_1 and expression_2 or expression_3
Look at the code:
a = "hello"
b = "will"
# Bool a:? B
print True and a or b
print False and a or b
This example via analog and-or a ternary operator, when the first expression expression_1 to True when the value of the whole expression is the value of the expression expression_2
Safety and-or
In fact, the use of analog and-or ternary operator is not safe manner above
If expression_2 value itself is False, then no matter what is the value expression_1, "expression_1 and expression_2 or expression_3" The result will be the expression_3.
It can be a simple line of code verification:
a = []
b = "will"
# Bool a:? B
print True and a or b
print False and a or b
Then in order to avoid this problem, you can use the following method to expression_2 and expression_3 stored in the list:
(Expression_1 and [expression_2] or [expression_3]) [0]
E.g:
a = []
b = "will"
# Bool a:? B
print (True and [a] or [b]) [0]
print (False and [a] or [b]) [0]
Effect of the code is run, even if expression_2 is False, but [expression_2] is still a non-empty list
to sum up
Through some simple examples that demonstrate the Python, and and or use.
And through the and-or approach to achieve the effect of the ternary operator. |
|
|
|