Python3 ternary conditional judgment expression (if else/and or)

if else expression usage:

c = a if a>b else b # First judge the if condition, if it is True, return a, otherwise return b

and or expression usage:

The principle is to use P and Q. If P is false in Python, then Python will not continue to execute Q, but directly determine that the entire expression is false (P value). If P is true, then continue to execute Q To determine the entire expression value; the same P or Q, if P is true, then Q will not continue

When the data are all Boolean types, the operation results are as follows:

true and true = True
true and false = False
false and true = False
false and false = False
true or true = True
true or false = True
false or true = True
false or false = False

When the data has Boolean type, the operation result is as follows:

12 and true = True
true and 12 = 12
false and 12 = False
12 and false = False
12 or true = 12
true or 12 = True
false or 12 = 12
12 or false = 12

The following conclusions can be drawn from the results:

(1) For AND, if there is False in the operation data, it is False; otherwise, return the rightmost data.

(2) For OR, if there is False in the operation data, return the remaining data; otherwise, return the leftmost data.

When none of the data is Boolean type, the operation result is as follows:

6 or 7 = 6
6 and 7 = 7

'a' or 'b' = 'a'
'a' and 'b' = 'b'

6 or 'a' = 6
6 and 'a' = 'a'

 It can be seen that the conclusion still applies.

In Python, AND has a higher priority than OR, so we can calculate the result according to the previous conclusion or principle. When writing code, it is best to write according to the principle. If there are a lot of and/or, you can use the conclusion to judge.

5 or 6 and 7 = 5
5 and 6 or 7 = 6
5 or 6 or 7 = 5
5 and 6 and 7 = 7

'a' or 'b' and 'c' = 'a'
'a' and 'b' or 'c' = 'b'
'a' or 'b' or 'c' = 'a'
'a' and 'b' and 'c' = 'c'

1 or 'b' and 'c' = 1
1 and 'b' or 'c' = 'b'
1 or 'b' or 'c' = 1
1 and 'b' and 'c' = 'c'

Special case None (does not contain booleans):

1. When comparing with a specific value: and returns None, or returns a specific value

'a' and None = None
None and 'a' = None
'a' or None = 'a'
None or 'a' = 'a'

1 and None = None
None and 1 = None
1 or None = 1
None or 1 = 1

None and 1 or 'a' = 'a'
1 and None or 'a' = 'a'
1 and 'a' or None = 'a'

2. When comparing with an empty value (such as: empty list/empty collection/empty dictionary): and returns the value on the left, or returns the value on the right

[] and None = []
None and [] = None
[] or None = None
None or [] = []

 

Guess you like

Origin blog.csdn.net/weixin_41611054/article/details/92841704