Why is my while loop not getting broken when condition is met within try-except statement?

I have some code which I would like to run into infinity unless a specific condition has been met. Within a try-except statement this condition is actually met and therefore I assumed the while loop would be broken, but apparently this is not the case. I am not sure why this does not break the while loop. Is try except overruling the while statement? Should I say after my try-except again something like test=test.copy() ? I’ve boiled it down to the code below for reproductive purposes.

test = None

while test==None:
    try:
        test="something changes in this try statement, should break while condition"
        print("even executed this line")
        #MY QUESTION IS WHY THE LOOP IS NOT BROKEN HERE

    except:
        print("this failed")

    print("try except passed, so here we do another thing to test to break the loop")
    test="after try-except statement changed test"

print(test)

prints:

#even executed this line
#try except passed, so here we do another thing to test to break the loop
#after try-except statement changed test

>Solution :

In the absence of a break or continue statement, the body of the loop executes in its entirety before the condition is checked again. After setting test = "something changes in this try statement, should break while condition", the condition test == None will evaluate to false, but not until the body of the loop completes. If you want to break *immediately, you have to test the condition explicitly:

test = None

while test is None:
    try:
        test = "something changes in this try statement, should break while condition"
        if test is not None:
            # This will exit the loop immediately.
            break
        print("even executed this line")

    except:
        print("this failed")

    print("try except passed, so here we do another thing to test to break the loop")
    test = "after try-except statement changed test"

Leave a Reply