0

Here is the code:

for i in range(12):
  for j in range(8):
    if i == j:
        break

print i
print j

My thought is: at first i is equal to 0 and j is equal to 0. This matches with the

i == j

condition and so

break

would be triggered. It would then exit the innermost for loop. So the value of j would be 0. Since the outer for loop doesn't get exited, i would continue to loop through all the elements in range(12) and at the end i would be assigned 11. So when I printed the values of i and j, they would be 11 an d 0 respectively.

However the result was:

i = 11 and j == 7

I would like to know which part in my argument above goes wrong.

Dennis
  • 175
  • 1
  • 3
  • 8
  • 3
    You seem to think that your inner loop never executes again after it breaked once, but on the second run of your outer loop, the inner loop starts over. – tkausl Sep 02 '18 at 12:55
  • 2
    your outer loop continues till the end `i = 11` and inner loop also continues till the end as `j < 8` and hence you get the final iteration of the loop, `i = 11, j = 7` – jkhadka Sep 02 '18 at 12:58

1 Answers1

1

with your code, the output is as below. So it the result is completely as expected and break is functioning well.
When ever i == j is true, the inner loop exists but the outer loop is still running and again loops the inner loop till either i==j is met or inner loop is completely iterated. Thus final output is i = 11 ; j = 7, the final result.

print 'i','j'
for i in range(12):
    for j in range(8):
        print i, j
        if i == j:
            #print " yes "
            break
    print "---------"

print i
print j

output is :

i j
0 0
---------
1 0
1 1
---------
2 0
2 1
2 2
---------
3 0
3 1
3 2
3 3
---------
4 0
4 1
4 2
4 3
4 4
---------
5 0
5 1
5 2
5 3
5 4
5 5
---------
6 0
6 1
6 2
6 3
6 4
6 5
6 6
---------
7 0
7 1
7 2
7 3
7 4
7 5
7 6
7 7
---------
8 0
8 1
8 2
8 3
8 4
8 5
8 6
8 7
---------
9 0
9 1
9 2
9 3
9 4
9 5
9 6
9 7
---------
10 0
10 1
10 2
10 3
10 4
10 5
10 6
10 7
---------
11 0
11 1
11 2
11 3
11 4
11 5
11 6
11 7
---------
11
7
jkhadka
  • 2,443
  • 8
  • 34
  • 56