7

I can't seem to figure out why this is an infinite loop in python??

for i in range(n):
    j=1
    while((i*j)<n):
       j+=1

shouldn't the outer loop go n times. incrementing j until its equal to n div i each time?

Matt Phillips
  • 11,249
  • 10
  • 46
  • 71

9 Answers9

36

i starts at 0, so the while condition stays always true; see the range docs for details.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Michał Marczyk
  • 83,634
  • 13
  • 201
  • 212
16

You can create a "trace" showing the state changes of the variables.

  1. n= 5; i= 0
  2. n= 5; i= 0; j= 1
  3. i*j < n -> 0 < 5: n= 5; i= 0; j= 2
  4. i*j < n -> 0 < 5: n= 5; i= 0; j= 3
  5. i*j < n -> 0 < 5: n= 5; i= 0; j= 4
  6. i*j < n -> 0 < 5: n= 5; i= 0; j= 5
  7. i*j < n -> 0 < 5: n= 5; i= 0; j= 6

etc.

You can prove that your trace is correct by inserting print statements.

When in doubt, print it out.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
12

i starts at zero, so the condition for the inner loop is always 0*j < n, which will always be true.

sth
  • 222,467
  • 53
  • 283
  • 367
7

Because the initial value of i is 0.

mob
  • 117,087
  • 18
  • 149
  • 283
4

The first value in i will be 0. 0 times anything is 0.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

because i is 0!! and i*j=0

Yin Zhu
  • 16,980
  • 13
  • 75
  • 117
2

range(n) starts at 0, not 1. 0 * j will always be less than n.

agf
  • 171,228
  • 44
  • 289
  • 238
Adam Crossland
  • 14,198
  • 3
  • 44
  • 54
1

On the first time through the outer loop, the inner loop becomes an infinite loop. It doesn't matter what happens after that. There's no "after infinity".

Matthias Wandel
  • 6,383
  • 10
  • 33
  • 31
0

i is 0 rewrite you loop like

for i in range(1,n):
j=1
while((i*j)<n):
   j+=1

using this version of the range function will create a range that starts at 1 instead of 0

RHicke
  • 3,494
  • 3
  • 23
  • 23