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

How to stop the execution of all loops on break instruction

I have to execute a for loop to traverse a list that resides inside a while loop like the following example:

while True:
    for i in range(0, 100):
        if i > 50:
            break
    print(i)

The problem I’m facing right now is that break instruction only stops the execution of the for loop, leaving the infinite while True always reach the print(i) line. So my question is, how can I add an instruction like break to close both while and for loops? And if there would be more than 2 nested loops, how could this be done?

The output of the last example is:

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

51
51
51
51
51
51
51
51
51
51
...

The desired functioning of the "break" line would lead to a null input for that example, which is the correct solution the code should give. The main goal here is to substitute break with an appropriate instruction to perform loop exiting.

>Solution :

I’d use a variable for that. Like this

run = True
while run:
    for i in range(0, 100):
        if i > 50:
            run = False
            break
    print(i)

— EDIT —

Even if above works, the highest ranked solution on How can I break out of multiple loops? is more elegant.

while True:
    for i in range(0, 100):
        if i > 50:
            break
    else:
       continue
    print(i)
    break
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