alwbtc
alwbtc

Reputation: 29495

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?

Upvotes: 16

Views: 27446

Answers (5)

mgibsonbr
mgibsonbr

Reputation: 22007

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.

Upvotes: 16

mrdos01
mrdos01

Reputation: 23

booked = False
for i in range(100, 200):
    if booked:
        break
    while True:
        for x in range(1, 3):
            if booked:
                break
            result = 0
            if result == 1:
                booked = True
        break
    continue

Upvotes: -1

OB1
OB1

Reputation: 149

What about this?

x = True 
while x:
    for i in range(20):
        if i>5:
            x = False
            break
        else:
            print(i)

Upvotes: -1

metakermit
metakermit

Reputation: 22351

The problem is that the outer loop's condition won't be checked until the inner loop finishes - and at this point i is already 100. From my perspective, the correct way to write this and get the desired output would be to put a guard inside the inner loop and break it when i reaches 10.

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

If there is some other reason why you want to break an outer loop while you're inside the inner loop, maybe you should let us in on the details to better understand it.

Upvotes: 1

sshannin
sshannin

Reputation: 2825

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

where time_to_break is the condition you're checking.

Or in general:

def loop_container():
  outer_loop:
    inner_loop:
      if done:
        return

loop_container()

Upvotes: 8

Related Questions