How does Python know a For loop is over?

Does Python know the For loop is over because of the indentation?

1 Like

In terms of knowing what is part of the loop and what isn’t - Yes, it is because of the indentation.

In terms of knowing when the loop stops iterating - It is based on the iterator variable defined in the loop. For example,

a = [1, 2, 3, 4]
for item in a:
    print(item)

The variable is item and Python internally knows when that iterator reaches the end and exits the loop based on that. This is a simplified explanation. If you wish to go a bit more in-depth with this, Python for loop is a good resource.

3 Likes

Hi, @everydaybest

The indents are needed for the parser that translates what you have written in bytecode.

The “for” loop is the so called syntax sugar loop based on the while loop and the iter() and next() functions.

When you pass a list into “for”, it applies the iter() function to it and makes it an iterator. Then the next() function is called asking for the next item. When the items end, the StopIteration exception is called. At this point, the For loop finishes.

image

1 Like

And this also

1 Like