What are the different types of loops good for?
In Python we have learned about several kinds of loops so far:
for-eachloop, 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.
- If you need the index for any reason, using
foris better. One reason to use the regular ol’
forloop 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.
whileloop 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
forloop that loops a specified number of times.
for-elseloops are useful for the same reasons, but have the added benefit of giving functionality when the loop exits normally.