0

My while loop doesn't stop the code when dlzka is more than 4. In the end dlzka goes up to 14 and I want to stop when it reaches the limit of items.

m = [[1, 1, 2, 1, 0, 1, 1, 1, 1, 1, 1, 1], 
[1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1], 
[1, 1, 0, 1, 2, 1, 1, 1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1]]

dlzka = 0
while dlzka <= len(m):
    for i in range(len(m)):
        for j in range(len(m[i])):
            for k in range(len(m)):
                if (m[i][j+k]) % 2 == 0:
                    dlzka += 1
                    print(m[i][j+k])
                    for z in range(1, len(m)):
                        if (m[i+z][j+k+z]) % 2 == 0:
                            print(m[i+z][j+k+z])
                            dlzka += 1
                    break
Mark
  • 55
  • 3
  • 4
    The `while` loop condition doesn't get checked every time `dlzka` is incremented, only when control actually reaches the top of the loop. If you want to break the `while` loop early, you'll need to break out of the appropriate `for` loop(s) early as well. – chepner Oct 24 '22 at 14:09
  • @chepner you can put that as an answer to the question – Emily Oct 24 '22 at 14:10
  • 1
    You can probably simplify this a bit. `i` never gets used except to index `m`, so you can simply iterate over `m` directly instead of iterating over `range(len(m))`. – chepner Oct 24 '22 at 14:11

0 Answers0