user3946189
user3946189

Reputation: 3

python how to exit a while loop and continue the parent loop?

when my code exits this while loop and if statement :

if im.getpixel((258,375)) == (30,37,43):
    battle = True
    print('lets Battle!!')
    time.sleep(10)
    leftClick()
    while battle == True:
        mousePos(503,487)
        leftClick()
        leftClick()
        time.sleep(5)
        im = screenGrab()
        if im.getpixel((258,375)) != (30,37,43) and im.getpixel((258,375)) != (99, 114, 121) and im.getpixel((258,375)) != (225, 225, 225):
            battle = False
            break
    print('battle Over')
    break

The code ends the parent while loop:

while 1 == 1:
    im = screenGrab()
    if im.getpixel((258,375)) == (30,37,43):
        battle = True
        print('lets Battle!!')
        time.sleep(10)
        leftClick()
        while battle == True:
            mousePos(503,487)
            leftClick()
            leftClick()
            time.sleep(5)
            im = screenGrab()
            if im.getpixel((258,375)) != (30,37,43) and   im.getpixel((258,375)) != (99, 114, 121) and im.getpixel((258,375)) != (225, 225, 225):
                battle = False
                break
        print('battle Over')
        break
    left(2)
    right(2)

I have been trying for ages but I can't get left() and right() to run and the loop to continue after the if statement ends.

Thanks for your help.

Upvotes: 0

Views: 934

Answers (2)

rajesh.kanakabandi
rajesh.kanakabandi

Reputation: 324

Break exits the current loop(while or for) not 'if' or 'else'. Use 'continue' to break the current iteration. And your code has 2 breaks remove the outer break and it should work as expected.

Upvotes: 0

Pierre Criulanscy
Pierre Criulanscy

Reputation: 8686

You are calling breakafter your printstatement :

print('battle Over')
        break

Your first breakstatement exits the second while and the breakmentioned above exits your first while.

Simply remove the breakstatement if you do not want to exit the parent while after the if statement.

Upvotes: 1

Related Questions