Python Why Order Matters in an 'and' Statement

  • Thread starter Thread starter Taylor_1989
  • Start date Start date
  • Tags Tags
    Python
AI Thread Summary
The discussion centers on the importance of the order of conditions in an 'and' statement in Python, particularly in relation to avoiding index errors. The original code works because it checks the length of the string before accessing its indices, while the reordered condition leads to an out-of-range error due to the evaluation order. Participants explain that many programming languages use short-circuit evaluation, meaning if the first condition is false, the second condition is not evaluated, preventing errors. Suggestions for code optimization include using string slicing instead of concatenation and improving variable names for clarity. The conversation emphasizes learning and improving coding practices through problem-solving.
Taylor_1989
Messages
400
Reaction score
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.

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 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 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 sysprog, Ibix and jim mcnamara
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.
I tried a web search "the loss of programming ", and found an article saying that all aspects of writing, developing, and testing software programs will one day all be handled through artificial intelligence. One must wonder then, who is responsible. WHO is responsible for any problems, bugs, deficiencies, or whatever malfunctions which the programs make their users endure? Things may work wrong however the "wrong" happens. AI needs to fix the problems for the users. Any way to...

Similar threads

Back
Top