-1

I have to execute a for loop to traverse a list that resides inside a while loop like the following example:

while True:
    for i in range(0, 100):
        if i > 50:
            break
    print(i)

The problem I'm facing right now is that break instruction only stops the execution of the for loop, leaving the infinite while True always reach the print(i) line. So my question is, how can I add an instruction like break to close both while and for loops? And if there would be more than 2 nested loops, how could this be done?

The output of the last example is:

51
51
51
51
51
51
51
51
51
51
...

The desired functioning of the "break" line would lead to a null input for that example, which is the correct solution the code should give. The main goal here is to substitute break with an appropriate instruction to perform loop exiting.

Cardstdani
  • 4,999
  • 3
  • 12
  • 31
  • 4
    Put it in a function and use `return`? – Guy Jun 21 '22 at 09:12
  • @guy I thought about this solution but the return of my function can't be instead of break, because it has to perform more computations – Cardstdani Jun 21 '22 at 09:13
  • You will completely lose control over your code if you try to exit an arbitrary amount of loops at once. – matszwecja Jun 21 '22 at 09:13
  • 1
    @Cardstdani Then make those computations. You can create multiple functions, you know. – matszwecja Jun 21 '22 at 09:14
  • Throw an exception? Delete the `while True:`? I suspect this might be an AB issue, though. – Ken Y-N Jun 21 '22 at 09:14
  • @matszwecja, I'd say it sometimes is a good idea to exit more than one loops. Depends on situation. – ex4 Jun 21 '22 at 09:15
  • 1
    @KenY-N [XY Problem](https://xyproblem.info/), you mean? – matszwecja Jun 21 '22 at 09:16
  • 1
    @Cardstdani It's so sad that the question is closed.I think `for... else...` its a good idea. If not break in `for`, it will execute `break` in else ``` while True: for i in range(0, 100): if i > 50: break else: break print("I > 50") break ``` – Lanbao Jun 21 '22 at 09:19
  • 1
    The question has been raised zillion of times, here and elsewhere. It has even been formalized as a PEP, but it was [rejected](https://mail.python.org/pipermail/python-3000/2007-July/008663.html) by GvR for both technical and "code average quality" reasons – gimix Jun 21 '22 at 09:29
  • 1
    @CN-LanBao The [second answer on the dup](https://stackoverflow.com/a/3150107/1270789) suggests the `for...else` construct. – Ken Y-N Jun 21 '22 at 10:13

1 Answers1

2

I'd use a variable for that. Like this

run = True
while run:
    for i in range(0, 100):
        if i > 50:
            run = False
            break
    print(i)

--- EDIT ---

Even if above works, the highest ranked solution on How can I break out of multiple loops? is more elegant.

while True:
    for i in range(0, 100):
        if i > 50:
            break
    else:
       continue
    print(i)
    break
ex4
  • 2,289
  • 1
  • 14
  • 21