-1

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
Pydude
  • 149
  • 13
  • 2
    A function can't `break` on behalf of its caller. Control flow statements don't work like that. – user2357112 Feb 27 '22 at 10:03
  • You can call `destroy()` from anywhere, it doesn't have to be from within a loop. That's when the `break` command would cease to make sense. Hence, this simply isn't possible. – deceze Feb 27 '22 at 10:11
  • Does this answer your question? [break and continue in function](https://stackoverflow.com/q/13986884/6045800) – Tomerikoo Feb 27 '22 at 10:12

2 Answers2

1

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
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

Break or continue are part of loops. You can use them if there is a loop in your code. If you just use conditional statements you can't and you don't need to use break. Just remove it or put your code into loop.

Mateusz S.
  • 26
  • 7