Search code examples
pythonreturnbreak

Break out of outer function if condition in inner function fails


I have a function move() with long ass code which takes over a minute to run and during this time the condition to execute the function might no longer be true. At first I was looking for something to check if the statement was true before executing each new line of code but apperantly that doesn't exist (super strange).

My new idea was the following:

def breakk():
    if x==0 or y == 0 or z == 0:
        code
        code
        code
        return 

def move():
    if x==1 and y == 1 and z == 1: 
        code
        code
        breakk()
        code
        code
        breakk()
        code

But this doesn't work since the return in the inner function breakk() has no effect on the outer function move()

My current work around is just terrible.. :

breakkk=0
def breakk():
    global breakkk
    if x==0 or y == 0 or z == 0:
        code
        code
        code
        breakkk=1
         

def move():
    global breakkk
    if x==1 and y == 1 and z == 1: 
        code
        code
        breakk()
        if breakkk==1:
            breakkk=0
            return
        code
        code
        breakk()
        if breakkk==1:
            breakkk=0
            return
        code
        .....

move()

Solution

  • make the breakk() return a boolean and then check whether breakk() is true:

    def move():
        if x==1 and y == 1 and z == 1: 
            code
            code
            if breakk():
                return
            code
            code
            if breakk():
                return
            code