What are the different types of loops good for?



What are the different types of loops good for?


In Python we have learned about several kinds of loops so far:

  1. The for-each loop, which is great for iterating over each item in a list or dictionary or word - anything iterable. It doesn’t, however, give us the index of the current item we’re accessing.
  2. If you need the index for any reason, using for is better. One reason to use the regular ol’ for loop with an index number to work with is to check how many times you’ve looped so far, or what position you’re at in an iterable.
  3. The while loop comes in handy when you aren’t sure if you want to enter the loop at all. For example, if you’re looping to get user input until it’s valid, you definitely want to loop at least once, but you have no way of knowing how many times the user might give invalid input, so you couldn’t use a for loop that loops a specified number of times.
  4. The while-else and for-else loops are useful for the same reasons, but have the added benefit of giving functionality when the loop exits normally.

FAQ: Learn Python- Loops - Create your own