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

SyntaxError: 'break' outside loop when I use it in loop

Problem

Hi, I am have a problem. Well, I know that I can’t use break outside the loop but I use it in loop and still get an error.

What I do

I create a function that have a command break and use it in loop. I get an error. I can’t do something like this:

function()
break()

because my function have an if statment, for example:

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

do somthing
if that:
   break

Code

def destroy():
    i = o.index(rect)
    MAPh[i] -= 1
    if MAPh[i] <= 0:
        del o[i]
        del MAP[i]
        del MAPxy[i]
        del MAPh[i]
        break

for a in range(len(MAP)):
    ...
    destroy

>Solution :

The fact that a function is called from a loop doesn’t mean you can break the loop from it. The break statement must be directly in the scope of a loop, not implicitly.

If you want to break the loop when a condition in the function is fulfilled, you can change the function to return an indicator for the loop to break:

def destroy():
    ...
    if condition:
        return True
    return False

for a in range(len(MAP)):
    ...
    if destroy():
        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