-1

So here's simple structure of my code:

while condition:
    for i in range(num):
        for j in range(num):
            if arr[i][j] == something:
                #DO SOMETHING
                #ESCAPE 

I want to escape only the for loops and start over the iteration from arr[0][0] inside the while loop.

It also has to avoid checking the same value that was checked in the previous loop.

For example, if arr[1][1] == something so it goes over the if statement, for the next iteration, it should start from arr[0][0] again and skip checking arr[1][1].

I'm struggling with break statements and the skipping part.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Softly
  • 1
  • 1
  • Put the for loops in a function and call it from the while loop. Then return will exit the for loops. – quamrana Sep 02 '23 at 13:03

1 Answers1

0
checked_indices = set()  # Set to store the checked indices

while condition:
    for i in range(num):
        for j in range(num):
            if (i, j) not in checked_indices and arr[i][j] == something:
                # DO SOMETHING
                checked_indices.add((i, j))  # Add the checked index to the set
                break  # Escape the innermost for loop
        else:
            continue  # Continue to the next iteration of the outer for loop
        break  # Escape the outer for loop
    else:
        break  # Escape the while loop

# Continue with the rest of your code

  • checked_indices set is used to keep track of the indices that have been checked. If an index (i, j) has already been checked, it will be skipped in the next iteration.
  • break statements are used to escape the for loops when a match is found and to continue with the next iteration of the outer for loop or while loop when necessary.
Sauron
  • 551
  • 2
  • 11