Python Indent – Group Code Together

In python, the main way of formatting your code will be through indents. Indentation is tabs of white pass that ‘group’ code together with each other.

For example, if you are using a for loop, every thing under the loop that is indented will be run with the loop. Once you go back to 0 indents, then python will know that you’re done with the loop code.

for i in range (5):
    print (i) # This line is indented once
    print ("This is my loop") # This line is also indented once
    print () # Finally, this line is also indented
print ("Ended Loop") # This line is back to 0 indents

Python Indents Code Sample

Let’s look at a quick code sample


Python Indentation

In python, the way you'll be formatting your code is mostly through indentation. This means putting different lines of code on different indents so that python knows which pieces go together.

Let's look at different indents of code. These groups of indents will form blocks

In [1]:
def my_function(): # This line does not have any indents
    print ("This is my function") # This line is indented once
In [4]:
for i in range (5):
    print (i) # This line is indented once
    print ("This is my loop") # This line is also indented once
    print () # Finally, this line is also indented
print ("Ended Loop") # This line is back to 0 indents
0
This is my loop

1
This is my loop

2
This is my loop

3
This is my loop

4
This is my loop

Ended Loop

All of the 'print' lines in the for loop above are on the same indent.

Link to code above

Check out more Python Vocabulary on our Glossary Page