You can use the all
option to check for each variable.
OPTION_1 if all(x in (0,1,2) for x in (i,j)) else OPTION_2
With this, you can check as many variables as you want or as many values you want.
OPTION_1 if all(x in range(3) for x in (a,b,c,d,e,f)) else OPTION_2
This will be equivalent to checking :
if a in (0,1,2,) and b in (0,1,2,) and c in (0,1,2,) and d in (0,1,2,) and e in (0,1,2,) and f in (0,1,2,)
The all
option will check if each if statement is True
. If all of them are True
, then all
will be set to True
. It will break as soon as the first one is False
. Similar to all
, you can use any
as well. any
works when you want to check for any one of them matching the condition. Normally used when you want to use the or
option.
In your if statement, you are giving the following:
if 4 and 2
In Python, 0 is false and 1 is True (any positive number greater than 0 is True).
The above statement results in:
if True and True
It always results the rightmost number. If the equation was a False, it will ignore the rightmost number and return False.
If condition such as if 2 and 4
will return 2
If condition such as if 4 and 2
will return 4
If condition such as if 0 and 4
will return 0
If condition such as if 4 and 0
will return 0
Your code is doing the following:
OPTION_1 if (i and j) in (0, 1, 2) else OPTION_2
Translated as:
OPTION_1 if (4 and 2) in (0, 1, 2) else OPTION_2
equates to:
OPTION_1 if (2) in (0, 1, 2) else OPTION_2
The output of this is True so resulting in OPTION_1.