A loop repeats a piece of code. That is the entire concept, and it is the reason a script is worth writing at all, since doing something once is rarely worth automating and doing it four hundred times is.
What are the two kinds?
One repeats for each item in a collection: for every file in this folder, for every row in this spreadsheet. The other repeats while a condition holds: while there are still pages to fetch, while the answer is not valid.
The first is far more common in beginner scripts and cannot loop forever, because collections end.
Why does the second kind cause trouble?
Because it only stops when its condition becomes false, and if nothing inside the loop changes that condition, it never does. The script runs until you stop it, which is the infinite loop everybody meets exactly once.
The fix is to check that something inside the loop moves towards the condition being false.
How do you stop one?
Interrupting the running program, which is a keyboard combination in a terminal and a stop button in most editors. Knowing which before you need it saves a moment of panic.
A loop writing to a file or making network requests is worth stopping quickly, since it will keep going.
What are the other loop mistakes?
- Off by one. Processing one too many or one too few, usually at the start or end.
- Modifying while looping. Changing a list you are iterating over, which behaves strangely.
- Loops inside loops. Which multiply, so a hundred by a hundred is ten thousand operations.
- Nothing accumulating. Calculating something inside the loop and never storing it.
Which of those is hardest to spot?
The last one. A loop that produces the right answer for each item and never keeps it produces no error, and the script finishes having done all the work and reported nothing.
How do you check a loop is doing what you think?
Print something each time round while developing. Seeing forty lines appear when you expected thirty-nine tells you more than reading the code, and removing the printing afterwards takes a second.
What about very large loops?
Worth adding a counter that reports progress. A script that appears frozen for ten minutes is indistinguishable from one that has crashed, and printing a line every hundred items removes the uncertainty.
Add a progress message every hundred items, and print a summary at the end saying how many were processed, how many were skipped and why.
What do beginners avoid unnecessarily?
Loops inside loops, which have a reputation for being slow. For a beginner's data sizes they are perfectly fine, and the readable version with two loops beats the clever version with one every time at this stage.
What is the mental model worth having?
A loop is a set of instructions given to somebody doing the same job repeatedly. If you cannot say what they are holding at the end of each round, and what makes them stop, the loop is not understood yet.