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?
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.
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.
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.
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.
i
starts at 0
, so the while
condition stays always true; see the range docs for details.
You can create a "trace" showing the state changes of the variables.
etc.
You can prove that your trace is correct by inserting print
statements.
When in doubt, print it out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With