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

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")
12 Likes

indentation means that all the codes you are writing is under less indented statement. If there is no indentation than it will be running outside the statement.

4 Likes

Just curious, how would we modify the code so that there is space between the executed printed list?

The print function automatically adds a newline at the end of each string when it’s called (this is why each new call to print is on a new line in your output).

You could work something out with multiple print functions (an empty print function for example would give you an empty line) but the simplest might be to modify the newline that gets added at the end of every string.

The standard print works like print(obj, end='\n'); you can modify the argument to the end parameter to use two newlines to get the result you wanted, print(obj, end='\n\n').

The syntax may be new to you here chances are keyword arguments and default values have yet to be introduced but you’ll eventually run into more of this when you cover functions in more detail.

5 Likes

indentation used for action command after loops (for [temporary variable] in [collection]: )
#mynote

1 Like