Ternary operators
Ternary operators are often referred to as conditional expressions in Python, which are based on the condition of True (TRUE)/False (false), and have ternary operations above Python 2.4.
Here is a pseudo-code and an example:
Pseudo code:
#如果条件为真,返回真 否则返回假condition_is_true if condition else condition_is_false
Example:
is_fat = Truestate = "fat" if is_fat else "not fat注意这个
It allows for quick judgment with a simple line, rather than using complex multiline if statements. This is useful most of the time and makes the code easy to maintain.
Another obscure usage is rare, it uses tuples, please continue to see:
Pseudo code:
#(返回假,返回真)[真或假](if_test_is_false, if_test_is_true)[test]
Example:
fat = Truefitness = ("skinny", "fat")[fat]print("Ali is", fitness)#输出: Ali is fat
This works because in Python, true equals 1, and false equals 0, which is equivalent to selecting data using 0 and one in the tuple.
The above example is not widely used, and Python players generally dislike that because there is no Python flavor (pythonic). Such usage can easily confuse real data with True/false.
Another reason for not using tuple conditional expressions is because the two conditions are executed in the tuple, and if-else the conditional expressions do not.
For example:
condition = Trueprint(2 if condition else 1 / 0)#输出: 2print((1 / 0, 2)[condition])#输出ZeroDivisionError异常
This is because the data is first built in the tuple and then indexed to the data with true (1)/false (0). if-elseconditional expressions follow a normal if-else logical tree, so it is best to avoid using tuple conditional expressions if the conditions in the logic are abnormal, or if they are recalculated (longer).
Python ternary operations