The environment is as follows
bash
$ python3 --version
Python 3.6.8
If there are multiple conditional expressions in the if statement, they are processed in order from the front. In the case of the and operator, when even one False conditional expression is found, Subsequent determination of the conditional expression is not performed, and the else part is processed.
The code below only differs in the order of the conditional expressions in the if statement, There will be a difference in the processing result.
test.py
l = [0] * 3
# l = [0,0,0]
print("0 <= i <When judging 3 first")
for i in range(4):
if 0 <= i < 3 and l[i] == 0:
print("i = {}success".format(i))
else:
print("i = {}Failure".format(i))
print("0 <= i <When judging 3 later")
for i in range(4):
if l[i] == 0 and 0 <= i < 3:
print("i = {}success".format(i))
else:
print("i = {}Failure".format(i))
Click here for the output result.
bash
$ python3 test.py
0 <= i <When judging 3 first
i =0 success
i =1 success
i =2 success
i =3 failure
0 <= i <When judging 3 later
i =0 success
i =1 success
i =2 success
Traceback (most recent call last):
File "test.py", line 13, in <module>
if l[i] == 0 and 0 <= i < 3:
IndexError: list index out of range
"When determining 0 <= i <3 first",
When ʻi = 3, it becomes False at the time of judgment of the first conditional expression,
0 <= i <3. The second
l [i] == 0` judgment has not been made.
On the other hand, in the case of "when determining 0 <= i <3 later",
Since the judgment of l [i] == 0
is performed first,
I get a list index out of range
error with ʻi = 3`.
I found it as a result of suffering that the sample code passed but my code did not pass ... the algorithm was the same.
With the and operator, even one Condition of False becomes False at some point, so it seems that subsequent conditional expressions are not processed.
Surprisingly, there were few articles that touched on this kind of content, so I summarized it.
Recommended Posts