1

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?

8
  • 1
    Does this answer your question? How can I break out of multiple loops? Commented May 26, 2022 at 17:06
  • 1
    Simplest way would be to put the loop inside a function and use return to "break" out of both loops. Commented May 26, 2022 at 17:06
  • Which j should be passed to executionfunction once you've called testfunction(i,j) on all the values of j? Commented May 26, 2022 at 17:08
  • 1
    Why can't you put the extra code in the else as well, before the continue? Commented May 26, 2022 at 17:10
  • 1
    Not sure what that means, but sounds wrong. What about what I asked about? Commented May 26, 2022 at 17:17

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.