0

I have a nested for and if structure as in below:

for i in range(n):
    for j in range(n):
        if i!=j:
            if i<j:
                if i!=0 and j!=0:
                    if max==saving[i,j]:
                        c1 = i
                        c2 = j

I want to break all of the if conditions and for loops when c1 and c2 are found. Where should I use "break" control ? Thanks.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 2
    if `i < j` then `i != j` is *also* true. – Martijn Pieters Jun 20 '14 at 11:02
  • 1
    In fact none of the conditionals are needed if the ranges for `i` and `j` are chosen more carefully. – Fred Foo Jun 20 '14 at 11:04
  • You have redundant if statements which you could combine into one and when you find c1 and c2 just put a `break` in the next line and it will exit from the most recent for loop. Please do some research before posting questions here. This is explained in the documentation at http://docs.python.org – Dhiraj Thakur Jun 20 '14 at 11:04
  • and one more comment - `break` is used for for loops, not for if conditions. `break` has nothing to do with if. – Korem Jun 20 '14 at 11:06
  • `for i in range(1, n):`, `for j in range(i + 1, n):` would give you loops that make all your conditions expect the last one obsolete. There is probably a *better method* to look for a given value in a `numpy` two-dimensional array, however. – Martijn Pieters Jun 20 '14 at 11:06

0 Answers0