- #1
Taylor_1989
- 402
- 14
- TL;DR Summary
- I am slightly confused as to why, in a IF statment that when using the AND operator the order in which the operator matters.
I am currently doing a leet code problem and came across something, I have not noticed before.
Here is a sample of the code I am working on.
Now the code above throws no error, however when I change the order of the and statement like the code below:
I get an out of range error as shown below:
So my question is why does order matter? I have always been under the impression that if you had an and statement with two True conditions then it would carry through the if statement, and if one of the conditions was False did not matter which way round it was it would not carry through the if statement.
I now assume this type of thinking is wrong.
Here is a sample of the code I am working on.
Python:
s = "10#11#12"
A=[]
B=[]
i=0
count=0
while i < len(s):
if i+2<len(s) and s[i+2]=='#':
A+=[(s[i]+s[i+1]+s[i+2])]
i+=3
print(i)
Now the code above throws no error, however when I change the order of the and statement like the code below:
Python:
s = "10#11#12"
A=[]
B=[]
i=0
count=0
while i < len(s):
if s[i+2]=='#' and i+2<len(s) :
A+=[(s[i]+s[i+1]+s[i+2])]
i+=3
print(i)
I get an out of range error as shown below:
Traceback (most recent call last):
File "<string>", line 10, in <module>
IndexError: string index out of range
So my question is why does order matter? I have always been under the impression that if you had an and statement with two True conditions then it would carry through the if statement, and if one of the conditions was False did not matter which way round it was it would not carry through the if statement.
I now assume this type of thinking is wrong.