0

I have two loops. I understand that I can use the break, continue and else statments after to break out of them, but because my loop has code also after the condition, which should only get executed for all the condition cases I think that it doesnt work. I would use code like this:

for i in range(10):
    for j in range(10):
        print(i*j)
        if testfunction(i,j):
            break
    else:
        continue  # only executed if the inner loop did NOT break
    break  # only executed if the inner loop DID break

Because of the required continue statement for the outer loop this does not work because the nested loop is not the only code in the outer for loop.

for i in range(10):
    for j in range(10):
        if testfunction(i,j):
            breaker = True
            break

    if breaker == True:
        break
    executionfunction(i,j) # this code should only be executed if i passed the test with all j's

How can I write this without using variables like breaker?

Flavio
  • 73
  • 7
  • Does this answer your question? [How can I break out of multiple loops?](https://stackoverflow.com/questions/189645/how-can-i-break-out-of-multiple-loops) – Ach113 May 26 '22 at 17:06
  • 1
    Simplest way would be to put the loop inside a function and use `return` to "break" out of both loops. – Ach113 May 26 '22 at 17:06
  • Which `j` should be passed to `executionfunction` once you've called `testfunction(i,j)` on all the values of `j`? – chepner May 26 '22 at 17:08
  • 1
    Why can't you put the extra code in the `else` as well, before the `continue`? – Kelly Bundy May 26 '22 at 17:10
  • -chepner The function will only be executed with the last value of J. Not with all of them. – Flavio May 26 '22 at 17:14
  • I cant put the else: continue break statment, because it will not allow the execution of executionfunction, wich should only be executed if all j values pass the testfunction. – Flavio May 26 '22 at 17:15
  • 1
    Not sure what that means, but sounds wrong. What about what I asked about? – Kelly Bundy May 26 '22 at 17:17
  • @KellyBundy Your comment is very smart, i did it and now it works. – Flavio May 26 '22 at 17:23

1 Answers1

1

I found the answer to be, to just include the code that I want to execute afterwards, in the else statment. As shown here:

for i in range(10):
    for j in range(10):
        print(i*j)
        if testfunction(i,j):
            break
    else:
        executecode(i,j) # only gets executed if testfunction was never true
Flavio
  • 73
  • 7