Python --If statement judgment behavior under multiple conditions (even though the order is different)

Introduction

The environment is as follows

bash


$ python3 --version
Python 3.6.8

Judgment behavior of if statement

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`.

end

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

Python --If statement judgment behavior under multiple conditions (even though the order is different)
Import error even though python is installed
Even if the development language is changed to python3 in Cloud9, version 2 is displayed in python --version
Execution order when multiple context managers are specified in the Python with statement
[For beginners] Unexpected behavior if "\" is included when setting the path in Python
The answer of "1/2" is different between python2 and 3
Python if statement
[Python] if statement
Check if the string is a number in python
[Nohup] Execution even if the terminal is turned off
Indent behavior of json.dumps is different between python2 and python3