Why Order Matters in an 'and' Statement

  • Context: Python 
  • Thread starter Thread starter Taylor_1989
  • Start date Start date
  • Tags Tags
    Python
Click For Summary
SUMMARY

The discussion centers on the importance of order in 'and' statements within Python code, specifically in the context of string manipulation. The user encountered an "IndexError" when changing the order of conditions in an if statement. The first version of the code checks the length of the string before accessing its indices, while the second version attempts to access an index before confirming its validity, leading to the error. The conversation highlights the concept of short-circuit evaluation in programming languages, where the second condition is not evaluated if the first condition is false.

PREREQUISITES
  • Understanding of Python programming language
  • Familiarity with string indexing and slicing in Python
  • Knowledge of conditional statements and logical operators
  • Basic concepts of error handling in Python
NEXT STEPS
  • Learn about Python's short-circuit evaluation in conditional statements
  • Explore string slicing techniques in Python for efficient data manipulation
  • Investigate best practices for naming variables in Python for code readability
  • Study error handling in Python to manage exceptions like IndexError
USEFUL FOR

Python developers, coding enthusiasts, and anyone looking to improve their understanding of conditional logic and string manipulation in Python.

Taylor_1989
Messages
400
Reaction score
14
TL;DR
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.

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.
 
Technology news on Phys.org
Many (not all) languages implement "shortcut" evaluation of if conditions. If you do a test like IF A AND B THEN, and it turns out that A is FALSE, then there's no point in even checking B - we know A AND B is FALSE whatever it is. So the computer can shortcut the operation. Ditto A OR B if A is TRUE - there's no point checking B in this case.

Knowing this, can you see why your first version works and your second one errors out?
 
  • Like
Likes   Reactions: sysprog, DrClaude, .Scott and 2 others
Incidentally, is what you are trying to achieve here just A=s.split("#")? This isn't what your code does, but I suspect it might be what you are aiming at.
 
Ibix said:
Many (not all) languages implement "shortcut" evaluation of if conditions. If you do a test like IF A AND B THEN, and it turns out that A is FALSE, then there's no point in even checking B - we know A AND B is FALSE whatever it is. So the computer can shortcut the operation. Ditto A OR B if A is TRUE - there's no point checking B in this case.

Knowing this, can you see why your first version works and your second one errors out?
Ah okay, I can see now thank you. Also, I am not aiming at splitting the given string. Basically I have to use a dictionary to convert there given string to a bunch of letter i.e decrypt the message, in this case, a-i is given the numbers 1-9 and j-z onwards is given by 10#, 11#,12#, etc.

I was just playing around with the idea of separating each of these into a list than checking against a dictionary, then from there looking at ways to optimize it the code.
 
Ah - I see. You can definitely optimise that, but I'll leave you to explore.

A couple of points, though. First, s[i]+s[i+1]+s[i+2] can be written s[i:i+3]. That becomes a huge saving when you want s[i:i+50]! Second, can I suggest more descriptive variable names? s for string isn't bad, but encryptedString would be better. And almost anything is better than A and B. Perhaps encryptedChars and decryptedChars?

Side note - my phone's autocomplete dictionary has "encrypted" but not "decrypted". Weird...
 
  • Like
Likes   Reactions: sysprog, jim mcnamara and Taylor_1989
Ibix said:
Ah - I see. You can definitely optimise that, but I'll leave you to explore.

A couple of points, though. First, s[i]+s[i+1]+s[i+2] can be written s[i:i+3]. That becomes a huge saving when you want s[i:i+50]! Second, can I suggest more descriptive variable names? s for string isn't bad, but encryptedString would be better. And almost anything is better than A and B. Perhaps encryptedChars and decryptedChars?

Side note - my phone's autocomplete dictionary has "encrypted" but not "decrypted". Weird...

First thank for the input, I can't believe I didn't think of using a slice method, thank you. To be honest I am just doing the leetcode problems, not for interview practice but more to learn about the python language itself. Also yes I agree my variable names should be more descriptive make sure of this next time
 
  • Like
Likes   Reactions: sysprog, Ibix and jim mcnamara

Similar threads

  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 11 ·
Replies
11
Views
1K
  • · Replies 29 ·
Replies
29
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
55
Views
7K
  • · Replies 6 ·
Replies
6
Views
3K
Replies
3
Views
3K
Replies
12
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 11 ·
Replies
11
Views
1K