Why do lines of code after a for loop have to be indented?


#1

Question

In this exercise, the code for the for loop has to be indented. Why does it have to be?

Answer

Indentation in Python is used to identify lines of code which are executed together. The block of code that is part of for loop has to be indented so that Python knows what to execute for each iteration of the loop. The point at which the indentation ends identifies the code that is NOT part of the for loop.

In the following code example, the print() call which outputs “In loop” will be repeated as part of the for loop but the next immediate line containing the print() which outputs “Not in loop” will execute only once.

for x in range(5):
    print("In loop")
print("Not in loop")