python if elif else in one line

>>> i=100
>>> a = 1 if i<100 else 2 if i>100 else 0
>>> a
0
>>> i=101
>>> a = 1 if i<100 else 2 if i>100 else 0
>>> a
2
>>> i=99
>>> a = 1 if i<100 else 2 if i>100 else 0
>>> a
1

Here is what the above code is Doing:
1. If i<100, a = 1 2. If i>100, a = 2
3. If i=100, a = 0

The reason a = 0 is because the first condition is true (i<100), so it sets a = 1. Then, the second condition is also true (i>100), so it sets a = 2. Since the value of a can’t be both 1 and 2, it just goes with the last assignment, which was a = 2.

You can also use the ‘or’ operator:

>>> i=100
>>> a = 1 if i<100 or i>100 else 0
>>> a
0
>>> i=101
>>> a = 1 if i<100 or i>100 else 0
>>> a
1
>>> i=99
>>> a = 1 if i<100 or i>100 else 0
>>> a
1

Here’s what the above code is doing:
1. If i<100 or i>100, a = 1
2. If i<100 or i>100 is false, a = 0

The reason a = 1 is because at least one of the conditions is true (i>100), so it sets a = 1.

You can also use the ‘and’ operator:

>>> i=100
>>> a = 1 if i<100 and i>100 else 0
>>> a
0
>>> i=101
>>> a = 1 if i<100 and i>100 else 0
>>> a
0
>>> i=99
>>> a = 1 if i<100 and i>100 else 0
>>> a
0

Here’s what the above code is doing:
1. If i<100 and i>100, a = 1
2. If i<100 and i>100 is false, a = 0

The reason a = 0 is because both conditions have to be true for a = 1, and in this case, they’re not.