Repeating until a condition changes
A while loop is useful when the number of iterations is not known in advance. The condition is checked before each iteration, so the loop can execute zero or many times.
Prevent infinite loops
Every loop needs a clear path toward termination. Update the state used by the condition, and for retries or polling add a maximum attempt count or timeout.
When to prefer for
If you are simply visiting every element of an existing collection, a for loop usually expresses the intent better. Use while when continuation depends on a changing condition rather than a fixed iterable.
Practice: build a three-attempt PIN prompt and make sure it stops immediately after a successful login.