Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading