Nesting Python ternary operators

When you want to write a ternary operator in Python (Note)

ex) I want to assign true for variable b when variable a is 10 or more, and false for other cases.

ternary_operator.py


b = true if a >= 10 else false

When you want to increase the conditions (note)

In the above case, it can be used when there are two conditional statements, but if you want to use the ternary operator even when there are more conditions, do this.

ex) I want to output'perfect' when the variable score is 100,'pass' when it is 60 or more and less than 100, and'fail' in other cases.

nested_ternary_operator.py


print('perfect' if score == 100 else 'pass' if score >= 60 and score < 100 else 'fail')

If ~ elif ~ else can be expressed by adding if after the expression of else It's cute that the ex status setting is loose

Recommended Posts

Nesting Python ternary operators
Nesting ternary operators in python
# 3 [python3] Various operators
Ternary operator (Python)
[Road to intermediate Python] Use ternary operators
About Python string comparison operators
Python