1

In a nested loop, after breaking out of the inner loop and going to the top loop it skips the parameters of the inner loop. Why and how can I fix this?

for i in range(5):
    for j in range(5):
        if i == j:
            print('Same Number')
        break

This code only prints 'Same Number' once. When 1 = 1. I'm not sure why j never changes but i does.

  • Does this answer your question? [How to break out of multiple loops?](https://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops) – Selcuk Jan 10 '20 at 02:57
  • @Selcuk I saw that earlier today and attempted to replicate it by adding an else and continue statement, but the output was still the same. I also don't know how to refactor (I'm still fairly newish to python). – Blanco Yisom Jan 10 '20 at 03:04
  • First this my first attempt at ansering so sorry if I’m doing it wrong. You are breaking out of the outer loop “i” not the inner loop “j” See for a better explanation https://stackoverflow.com/questions/40602620/how-to-break-out-of-nested-loops-in-python try indenting break one more time like this.for i in range(5): # print(i) for j in range(5): if (i==j): print("same number") # print(i,j) break – Gary Caine Jan 10 '20 at 03:57
  • Sorry couldn't get that to format right. just indent break one more time so you are only breaking out of the inner loop – Gary Caine Jan 10 '20 at 04:04

1 Answers1

1

The way you have it written right now, the inner loop will always break on the first iteration (when i = 0). This is why you are only seeing it print once, the outer loop is looping 5 times, however the inner loop only ever gets through the first iteration before hitting break.

See below, the break line should be nested inside the if statement so it only breaks from the inner loop when the two numbers match.

for i in range(5):
    for j in range(5):
        if i == j:
            print('Same Number')
            break
Yusef
  • 306
  • 1
  • 5