-1

I want to break main while loop using break statement inside if condition

a = 0
b = True
while b:
    print(a)
    while a < 10:
        if a == 8:
            b = False
            break       # want to break both while loops using this command
        else:
            print(a)
            a += 1

result should be 0 0 1 2 3 4 5 6 7

Deepu
  • 1

1 Answers1

0

Python doesn’t offer a way to break out of two (or more) loops at once, so the naive approach looks like this:

b = True
while b:
    print(a)
    while a < 10:
        if a == 8:
            b = False #Use this value to break out of top loop
            break
        else:
            print(a)
            a += 1
    if !b: #Use the value of b like this to break out of top loop
        break
Sanket Singh
  • 1,246
  • 1
  • 9
  • 26