#๐ how to avoid infinite loop
12 messages ยท Page 1 of 1 (latest)
@deft island
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.
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
just create a artificial limit of the number of repeat should happen (never should never reach normally)
@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.
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.