There are simple loops ( for element in set ) and complex loops. You probably already know how to write simple loops, but complex loops don't follow the same pattern and need some more sophisticated techniques to get them right.
In this video I talk about the techniques and apply them in an extended example to write a correct complex loop. Techniques include loop invariants, loop variants, and the loop condition.
The book I mentioned: https://www.amazon.com/Programming-Pearls-2nd-Jon-Bentley/dp/0201657880