The ternary operator allows testing a condition in a single line replacing the multiline if-else making the code compact.
[on_true] if [expression] else [on_false]
We can also use the direct Method by using tuples like (b, a) [a < b]
.
Let's look at an example
ck = True
print(2 if ck else 1)
print((1, 2)[ck])
Here both output is 2
. Now, if i change the output 2
& 1/0
Tuple always raise zero division error.
print(2 if ck else 1/0)
print((1/0, 2)[ck])
Same error for (2, 1/0)[ck]
. Ternary if-else is showing the correct result under any circumstances but why tuple raise the error 1/0
?