https://qiita.com/ganariya/items/fb3f38c2f4a35d1ee2e8
In order to study Python, I copied a swarm intelligence library called acopy.
In acopy, many interesting Python grammars and idioms are used, and it is summarized that it is convenient among them.
This time, we will learn Python's ternary operator.
The ternary operator is used in C ++ etc.
An operator that ends a statement that can be expressed by if-else with one line, such as conditional expression: true value: false value
.
Of course, the amount of description will be much shorter, but nesting the ternary operator will significantly reduce the visibility.
If you want to nest, be aware of reviewing the algorithm and writing it normally with an if statement.
Python's ternary operator
True value if conditional expression else False value
and
The order is different from C ++ and C language.
For me who use C ++ or C, this is a notation that feels quite strange. In C ++
I'm glad that it can flow naturally, but in the case of Python
I feel that the order is reversed and it is very difficult to do. I wonder if this is even possible with Vimmer.
For the time being, I will write an even-odd number judgment.
a = int(input())
s = "odd" if a % 2 else "even"
print(s)
I feel that the way of writing here is like English. I want to remember the order of true conditional expression and false first.
If there is a negative, it is troublesome, so if it is negative, output minus.
a = int(input())
s = "minus" if a < 0 else "even" if a % 2 == 0 else "odd"
print(s)
First, check if it is negative, and if it is negative, end with minus
.
If not, check even, odd again with the nested ternary operator.
Stop using the ternary operator! (moderately)
Recommended Posts