What are the different types of loops good for?

Question

What are the different types of loops good for?

Answer

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.
4 Likes

What do they mean by “for-each” ? And how does it differ from “for” ?

2 Likes

point 1 and 2 from the answer both use for keyword.

if you want elements from the iterable (could be string or string for example) you get:

for value in element:

to get the indexes:

for index in range(len(element)):

to get both python offers a built-in function:

for index, value in enumerate(element):
2 Likes

I see. That clarifies it. Thank you.

Hi, I am currently at the module titled ‘Introduction to Pandas’, I have not come come across the lesson on loops yet. where exactly in the course is the loop function covered? I have seen several applications of loops during my study, and yet, I have yet to find a lesson on it. Please help provide a reference to where the topic of loops is covered

python3 course (pro only):

https://www.codecademy.com/courses/learn-python-3/lessons/learn-python-loops?action=resume_content_item

python2 course:

https://www.codecademy.com/courses/learn-python/lessons/python-2-loops?action=resume_content_item

of the pro-intensive course, i am not sure.

1 Like

Just like stetim94 already explained, for-each is a reference to “for” loop in which you want to loop through all of the elements in the given list of elements and you don’t necessarily know the exact amount of the elements you are working with. It’s also worth noting, that some other programming languages have even a separate version of this command like “foreach”, “forEach”, “For Each”, etc. For this reason, I’m not quite sure if I like the way Python handles “for-each” loops, because I’m used to “foreach” from elsewhere, so when I think “for”, I usually don’t want to think “foreach”, because it confuses me, but I guess I will have to get used to it. :stuck_out_tongue:

1 Like