Search code examples
pythonfor-loopwhile-loopbreakflow-control

Python flow control break out confusion


I am trying to understand a complicated flow control that I cannot get to work so have simplified it and don't understand its workings either.

The simplified flow control is:

smurf = True
print('smurf status: ', smurf)
jackets = list(range(5))
print(jackets)

for j in jackets:
    print('la la la la', j, '\n')
    while smurf is True:
        print('jacket is :', j)
        if j == jackets[-3]:
            smurf = False
            break
            print('smurf is FALSIOOOO')
        j += 1
        print('smurf with jacket ',j-1, ' be ok')
print('END OF SMURFGATE') 

The output is:

smurf status:  True
[0, 1, 2, 3, 4]
la la la la 0 

jacket is : 0
smurf with jacket  0  be ok
jacket is : 1
smurf with jacket  1  be ok
jacket is : 2
la la la la 1 

la la la la 2 

la la la la 3 

la la la la 4 

END OF SMURFGATE

What I thought would happen (but does not) is once the j iteration reaches the test condition the while loop will stop and the flow control will skip onto the last line of the script and print 'END OF SMURFGATE'.

Desired output:

smurf status:  True
[0, 1, 2, 3, 4]
la la la la 0 

jacket is : 0
smurf with jacket  0  be ok
la la la la 1
jacket is : 1
smurf with jacket  1  be ok
la la la la 2
jacket is : 2


END OF SMURFGATE

Solution

  • You're missing one additional break for the for-loop, now you're only breaking the while loop. Try this:

    smurf = True
    print('smurf status: ', smurf)
    jackets = list(range(5))
    print(jackets)
    
    for j in jackets:
        print('la la la la', j, '\n')
        while smurf is True:
            print('jacket is :', j)
            if j == jackets[-3]:
                smurf = False
                break
                print('smurf is FALSIOOOO')
            j += 1
            print('smurf with jacket ',j-1, ' be ok')
        break # To escape the for-loop
    print('END OF SMURFGATE') 
    

    Output:

    smurf status:  True
    [0, 1, 2, 3, 4]
    la la la la 0 
    
    jacket is : 0
    smurf with jacket  0  be ok
    jacket is : 1
    smurf with jacket  1  be ok
    jacket is : 2
    END OF SMURFGATE