Question

I have a following code in which I am using break statement inside a for loop in the following way:

noBreak = True
def scanShift():
    i = 0
    for i in range(0,29):
        if s[i] < current < s[i+1]:   #1st if loop
            global noBreak
            if i in [1,3,5,7]:        #2nd if loop
                noBreak = False

            else: noBreak = True      #line1

            break
    return i

In case '1st if loop' condition is matched when i = 3 then after going to '2nd if loop' the program comes out of '1st if loop' without reaching the break statement. Thus my question is why it is happening in this way, shouldn't after executing '2nd if loop' it should go to the break statement and then break out of the for loop?

Was it helpful?

Solution

Just realized I don't have python currently installed on this computer.

Can you try running this to see what happens?

noBreak = True
i = 0
for i in range(0,29):
    if 6 < i < 8:   #1st if loop
        if i in [1,3,5,7]:        #2nd if loop
            print "here"
            noBreak = False
        else: 
            print "there"
            noBreak = True      #line1
        print "Going to break out of loop"
        break
print i

I hope the output is something along the lines of:

>>here
>>Going to break out of loop
>>7
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top