The ternary operator puts together simple if-else statements on one line, making them easier to read.
For example, if you want to display foo as the value when v is greater than 10, and bar otherwise, write it in an if-else statement and write it in 4 lines.
if-4 lines when written in else statement
In [22]: for v in range(-5, 15):
...: if v > 10:
...: p = 'foo'
...: else:
...: p = 'bar'
...: print(v, p)
...:
-5 bar
-4 bar
-3 bar
-2 bar
-1 bar
0 bar
1 bar
2 bar
3 bar
4 bar
5 bar
6 bar
7 bar
8 bar
9 bar
10 bar
11 foo
12 foo
13 foo
14 foo
The grammar of the ternary operator is
(variable) = (Value when the condition is True) if (conditions) else (conditionsがFalseのときの値)
The ternary operator can be written in one line.
One line when written with a ternary operator
In [26]: for v in range(-5, 15):
...: p = 'foo' if v > 10 else 'bar'
...: print(v, p)
-5 bar
-4 bar
-3 bar
-2 bar
-1 bar
0 bar
1 bar
2 bar
3 bar
4 bar
5 bar
6 bar
7 bar
8 bar
9 bar
10 bar
11 foo
12 foo
13 foo
14 foo
** Here, the if-else statements between the for-print statements are summarized by the ternary operator. ** **
When adding one condition and outputting'foobar' if it is less than 0, add ʻelif`.
This will output "'foo' if it is greater than 10,'foobar' if it is less than 0, and'bar' otherwise."
if-Two or more else statement conditions
In [36]: for v in range(-5, 15, 1):
...: if v > 10:
...: p = 'foo'
...: elif v < 0:
...: p = 'foobar'
...: else:
...: p = 'bar'
...: print(v, p)
...:
-5 foobar
-4 foobar
-3 foobar
-2 foobar
-1 foobar
0 bar
1 bar
2 bar
3 bar
4 bar
5 bar
6 bar
7 bar
8 bar
9 bar
10 bar
11 foo
12 foo
13 foo
14 foo
The grammar for nesting ternary operators is
(variable) = (Value when the condition is True) if (conditions) else (conditionsがFalseのときの値) if (conditions) else (conditionsがFalseのときの値) ...if-()-else-()Connect infinitely
Nested ternary operator
In [38]: for v in range(-5, 15, 1):
...: p = 'foo' if v > 10 else 'foobar' if v < 0 else 'bar'
...: print(v, p)
-5 foobar
-4 foobar
-3 foobar
-2 foobar
-1 foobar
0 bar
1 bar
2 bar
3 bar
4 bar
5 bar
6 bar
7 bar
8 bar
9 bar
10 bar
11 foo
12 foo
13 foo
14 foo
Qiita --Ternary Operator (Python)
Recommended Posts