-1

I'm trying to create a for loop in a while loop and I need to break the outside while loop when idx = 3, but for some reason it doesn't work.

arr = [-1, -1, -1, -1, -1]
indices = [0, 1, 2, 3, 4]
idx = 0

while idx < 3:
    for item in indices:
        arr[item] = idx
        idx += 1
        print('idx', idx)

Expected output: idx 1 idx 2 idx 3

Actual output: idx 1 idx 2 idx 3 idx 4 idx 5

Is there something I'm missing?

4 Answers4

1

I suggest using break statement inside for:

while idx < 3:
    for item in indices:
        arr[item] = idx
        idx += 1
        print('idx', idx)
        if (idx >=3):
             break
jhihan
  • 499
  • 4
  • 8
0

Can do:

arr = [-1, -1, -1, -1, -1]
indices = [0, 1, 2, 3, 4]
idx = 0

    while idx < 3:
        for item in indices:
            arr[item] = idx
            idx += 1
            print('idx', idx)
            if idx < 3:
                continue
            else:
                break

Note that the actual output of your original code makes sense because idx < 3 is checked before every iteration, but not within iterations. So once it was established that idx is indeed less than 3, the for loop takes place, and that will print and increase idx without checking its value. If you want idx to be checked and stop when reaches a certain point, you have to add the clause I added.

zabop
  • 6,750
  • 3
  • 39
  • 84
0

you can had a condition in the second loop to break if it is equal to 3

if idx == 3:
    break

edit: but you can also follow this advice https://stackoverflow.com/a/189685/9936992

  • This worked. The while loop was unnecessary after adding it so I took it off and simply had the for loop and this statement –  Oct 15 '20 at 14:32
  • great then in your future question try to give more detail about what you are trying to achieve with your code – Chris Golden Oct 15 '20 at 15:20
0

You simply need to add an if statement in your for while and then pass a break statement in if block, like this:

arr = [-1, -1, -1, -1, -1]
indices = [0, 1, 2, 3, 4]
idx = 0

while idx < 3:
    for item in indices:
        arr[item] = idx
        idx += 1
        print('idx', idx)
        if idx == 3:
            break

Now when idx is equal to 3, the loop will be terminated.

Have Fun :)

Saeed
  • 3,255
  • 4
  • 17
  • 36