Search code examples
pythonfor-loopwhile-loopbreak

How to break while loop in an inner for loop in python?


while doesn't break when i>10 in for loop:

i = 0
x = 100
while i<=10:
    for a in xrange(1, x+1):
        print "ok"
        i+=1

and it prints "ok" 100 times. How to break the while loop when i reaches 10 in for loop?


Solution

  • Until the inner loop "returns", the condition in the outer loop will never be re-examined. If you need this check to happen every time after i changes, do this instead:

    while i<=10:
        for a in xrange(1, x+1):
            print "ok"
            i+=1
            if i > 10:
                break
    

    That break will only exit the inner loop, but since the outer loop condition will evaluate to False, it will exit that too.