Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is this an infinite loop in python?

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?

like image 276
Matt Phillips Avatar asked Jan 12 '10 17:01

Matt Phillips


People also ask

What causes an infinite loop in Python?

A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.

How do you fix an infinite loop in Python?

You can stop an infinite loop with CTRL + C . You can generate an infinite loop intentionally with while True . The break statement can be used to stop a while loop immediately.

What causes a loop to be infinite?

Usually, an infinite loop results from a programming error - for example, where the conditions for exit are incorrectly written. Intentional uses for infinite loops include programs that are supposed to run continuously, such as product demo s or in programming for embedded system s.

How do you know if a loop is infinite in Python?

If the Python program outputs data, but you never see that output, that's a good indicator you have an infinite loop. You can test all your functions in the repl, and the function that does "not come back" [to the command prompt] is a likely suspect.


2 Answers

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

like image 193
Michał Marczyk Avatar answered Sep 20 '22 03:09

Michał Marczyk


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.

like image 29
S.Lott Avatar answered Sep 21 '22 03:09

S.Lott