Search code examples
pythonrect

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:

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