How does Python know a block of code is in a loop?

Python identifies blocks using indentation. All the statements in a particular block need to be indented at the same level, though you can use any amount of indentation, but all the statements in a particular block need to have the same indentation level. So in your example, Statement 2 is indeed outside the for loop in the same level of indentation, hence it is in the same block as the for loop.

One important thing to note, even though it is allowed to use different level of indentation for different blocks, (including mixing tabs and spaces, you should not do that, and you should always use the same amount of indentation throughout), meaning if you indent one block as four spaces from the previous block, you should ideally indent like that always.

PEP-0008 (the style guide for Python) suggests to use four spaces as indentation.


This is indeed done by indentation. So in your example, statement 1 is in the for-loop, statement 2 isn't. You can use spaces and tabs as indentation, as long as you are using the same thing everywhere in the code.

An example of a nested for-loop:

for i in range(5):
    for j in range(10):
        print j
    print i
print 'Done!'

print j is done in the j-for-loop. print i is done in the i-for-loop. Done! will only be printed once, in the end.

Tags:

Python