#๐Ÿ”’ how to avoid infinite loop

12 messages ยท Page 1 of 1 (latest)

deft island
#

Hey!
is there a good technique or trick to have in mind when infinite loops occurs in code, i know that for infinite while loops, the trick is not to have the condition to be true, but for me it could be bit hard sometimes to understand what this actually means or apply it correctly in different scenarios

how do you do it?

bronze flaxBOT
#

@deft island

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

visual nova
#

Infinite loops usually happen with a recursive item, uncapped variable, or forever-true variable

#

Recursive items are easy, just set a counter for recursion and stop it when it reaches that counter

#

Uncapped variables are the same, just set a cap (example:)

if var == 5:
  break
#

Forever true variable are also similar, just set it to false after something is achieved or after a certain amount of repetitions

#

One likely way to get an infinite loop is to have a cap that is below the starting value

#

When in doubt, debug the code and use breakpoints

amber pawn
#

just create a artificial limit of the number of repeat should happen (never should never reach normally)

ebon sinew
#

@deft island the basic deal is to ensure that your loop terminates. Every iteration of the loop should advance towards that limit, whatever it is. Perhaps you're consuming something like lines of text from a file - if your loop doesn't pick up at least one, it won't finish. If you're doing something more complex, for example reading lines and then consuming items off the line (invented example, column values from a CSV like 1,2,3,4), consume at least one, only getting a new line when they're consumed. The point being that every time around the loop something always brings you closer to finishing.

A loop has 2 characteristics:

  • an invariant, some set of conditions which is always true at the top of the loop and the bottom meaning that things are sane
  • a bound: the condition when the loop should finish

Every iteration should preserve the invariant (i.e. don't so something which is nonsense) and advance towards the bound. You only run forever if you never reach the bound.

bronze flaxBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.