Generally, the difference in the application between the two loops is that you use a while loop when you’re intending to run a process until a condition changes or until a condition is met.
Examples of using a while loop:
- Monitoring the temperature of a system. Shut system off when ambient temperature reaches 180 F.
Edit:
Make sure to design your loops carefully as you don’t want to inadverdently have your script stuck in an infinite while loop keeping other parts of your script from running. This is more susceptible to happen in a while loop versus in a for loop.
A for loop, on the other hand, is generally used to process a number of known items within a data structure (i.e., list, dictionary, tuple, set, etc.).
Examples include but are not limited to:
- Search a name within a list of strings. If found, break.
- Capitalize the first letter of every string in a list.
- Take the square of every number within a list.
- Call a set of functions in a dictionary.
Not sure if better, at least in my experience. As stated above, it has to do more with what you are attempting to accomplish in your script; that is, what is your objective.
