Python and-or, pythonand-or
[Original] The and-or in python is often used to implement the ternary operators like C :? ,
The statement is xxx and xxx or xxx, so that multiple expressions can be implemented in one line.
Code:
(1) def Judge ():
If a> 10:
Return "big"
Elif a> 5:
Return "middle"
Else:
Return "small"
(2) def judge (B ):
Return B> 10 and "big" or B> 5 and "middle" or "small"
(1) and (2) achieve the same effect.
However, it should be noted that and-or is not fully equivalent to the ternary operator, because a and B or c,
If B is a false value, c will be returned (the computer is relatively lazy --!)
However, there are skills to achieve this:
Def choose (bool, a, B ):
Return (bool and [a] or [B]) [0]
If bool is true, [a] is returned. Otherwise, [B] is returned. As mentioned above, the computer is very lazy.
Determine whether the value before and is true. If it is true, then xxx and xxx are true.
[0] at the end of return is used to output results in numbers rather than in lists: Add [0] 7 without [0] [7]
Example: choose (True, 0, 6)
>>> 0
Choose (True, 7, 6)
>>> 7
Choose (False, 0, 6)
>>> 6
Choose (False, 7, 6)
>>> 6
If [0] is not added,
Choose (True, 0, 6)
>>> [0]
That's all.
I use python QAQ
Come on !!!
Reference: http://python.jobbole.com/81233/