What is Indentation in Python?

Python indentation is space before the line of code in your program. Indentation is a way to tell the python interpreters that this is a block of code.

Block of code is packaged code that is executed according to our specified condition so it is our moral responsibility that we tell computers what is a block of code because otherwise the computer will try to read everything line by line as it does always and it will not understand which one is a line and which one is block.

Let’s understand with one block of code! I have written a block of code to tell the computer to print ‘GO!’, if the signal is green. Let’s deal with this!

signal = "green"

#This is a block of code

if signal == "green" :
  print("GO!")         #see this statement is indented. There are 2 spaces before print and it is not the same level as if.

We can see the code above is indented to tell the computer to interpret this as a block of code. Don’t worry about the condition, we are going to cover this later.

Want to see if the code is not indented?

#This is a block of code

if signal == "green" :     
print("GO!")

"""
output:

File "<ipython-input-2-89ff25f8f70c>", line 3
    print("GO!")
        ^
IndentationError: expected an indented block

"""

It throws the Indentation error. The reason is, the interpreter is reading both as lines, not as a block.

Indentation is a very important concept to understand in Python. It can be a source of frustration for a beginner or someone who has used some other programming language.

For other programming languages, the block of code is represented within {} curly braces while in python it is the indentation that represents a block of code.

You can see a comparison of Python and JavaScript. In Python, the block of code is indented after the colon while in JavaScript, you see them it is bundled in curly braces.


The basic rule for indenting Python code is The first statement in a basic block, and each subsequent statement after it must be indented by the same amount. One of the distinctive features of Python is its use of indentation to highlighting the blocks of code.

If a block has to be more deeply nested, it is simply indented further to the right. You can understand it better by looking at the following lines of code:

A little history
The historical reasons for why Python uses indentation vs the arguably more commonly accepted curly braces {} are outlined in an article on the history of Python by Guido van Rossum — the creator of Python.

## Write nested if-else code with few lines of code (mostly print statement) before and after if block

print("1st Statement")  #Statement 1
print("2nd Statement")  #Statement 2

i = 2                   #Statement 3

if (i == 3) :           #Statement 4 (A block of code!)
print("3rd Statement")


File "<ipython-input-3-bda1355eed5f>", line 5
    print("3rd Statement")
        ^
IndentationError: expected an indented block

In the above example, statement 1, statement 2, and statement 3 are statements that python can easily interpret.

After statement 3 it goes to statement 4 and sees one if statement. This is a block of code that has to be executed when i equals 3.

The problem is that line 5 also is a line and not part of the statement 4 block because it is not indented and it is not possible for the Python interpreter to understand and execute this.

The correct way to write the above code is:

print("1st Statement")
print("2nd Statement")

i = 2

if (i == 3) :
   print("3rd Statement") #See, we have given whitespaces and it is taking this as a block!

Let’s have a look at another example! Try to figure out which is a block of code.

print("1st Statement")
print("2nd Statement")
i = 2
if (i == 3) :
  print("3rd Statement")
  print("4th Statement")
print("5th Statement")

"""
output:

1st Statement
2nd Statement
5th Statement

"""

Let’s talk about the above code. We can see there is one block of code in if statement and it has the next two print statements indented-

print(3rd Statement)

print(4th Statement)

Python interpreters will take these as a single block of code because these are indented at the same level.

And the block has to run when i equals 3, which is not true in this case, so both the 3rd and 4th Statements are not printed.

While the 5th Statement is not indented that means this is not part of the block and is a separate statement. Hence, when i is not equal to 3, still 5th Statement is printed in the output.

Easy, right? 🙂

print("1st Statement")
print("2nd Statement")
i = 3
if (i == 3) :
  print("3rd Statement")
  print("4th Statement")
print("5th Statement")

"""
output:

1st Statement
2nd Statement
3rd Statement
4th Statement
5th Statement

"""

 

print("1st Statement")
print("2nd Statement")

i = 3
if(i == 3) :
  print("3rd Statement")
  print("4th Statement")
  print("New Statement")

print("5th Statement")

if(i == 2) :
  print("6th Statement")
  print("7th Statement")

"""
output:

1st Statement
2nd Statement
3rd Statement
4th Statement
New Statement
5th Statement

"""

How to Solve “IndentationError: expected an indented block”?

# Code block is defined using indentation in python 
# 2nd line of the below code has no spaces to define the function 'a' code block

def a():
print("foo")

"""
output:

File "<ipython-input-5-34d000d9a565>", line 2
    print("Bar")
        ^
IndentationError: expected an indented block

"""

 

How to Solve “SyntaxError: unexpected EOF while parsing”?

 

# A conditional block cannot be left vacant, we may use the "pass" keyword with proper indentation to leave it vacant
  
if True:


"""
output:

File "<ipython-input-22-a4e6d8adcb65>", line 2
    if True:
    ^
IndentationError: unexpected indent

"""
# Hitting enter after the conditional or functional code blocks automatically starts from an indented line

def a():
   print("foo")

How to Solve “IndentationError: unexpected indent”?

 

# Giving spaces after an already indented line starts a new code block 
# Extra attention should be given to defining blocks of code

def a():
   print("foo")
     print("bar")

"""
output:

File "<ipython-input-12-e974b715af76>", line 6
    print("bar")
    ^
IndentationError: unexpected indent

"""

 

## Practise Problem
age = 10
can_drive = None

if age >= 18:
  print('You can drive')
    can_drive = True

 

How to Solve “IndentationError: unindent does not match any outer indentation level” ?

 

if True:
    if False:
        print('foo')
   print('bar')

"""
output:

bar

"""

 

## Practise Problem

if(user == "Joey"):
print("Super secret powers enabled!")
print("Revealing super secrets")

 

I’m still getting an IndentationError but my program appears to be correctly indented. What do I do?

If your program visually appears to have correct indentation, but your still getting an IndentationError you have most likely mixed tabs with spaces. This will sometimes cause Python to raises strange errors. Let’s understand. What does “TabError: inconsistent use of tabs and spaces in indentation” mean? for an more in-depth explanation of the problem.

How to Solve “TabError: inconsistent use of tabs and spaces in indentation”?

 

for i in [1, 2, 3, 4]:
  print(i) # with tab
  print(i) # with 4 spaces

"""
output:

1
1
2
2
3
3
4
4

"""

 

Here is a picture which visually shows the whitespace in the above program. Gray dots are spaces, and gray arrows are tabs:

Special cases

Note Python will not always raise a TabError if you mix tabs and spaces into your program. If the program indentation is unambiguous, Python will allow tabs and spaces to be mixed. For example:

How to Solve “SyntaxError” related indentation problems?

Although not often, sometimes certain SyntaxError exceptions are raised due to incorrect indentation. For example, look at the code below:

if True:
    pass
pass # oops! this statement should be indented!.
else:
    pass

"""
output:

File "<ipython-input-1-893ee32faa31>", line 4
    else:
       ^
SyntaxError: invalid syntax

"""

 

Although Python raises a SyntaxError, the real problem with the above code is that the second pass statement should be indented. Because the second pass isn’t indented, Python doesn’t realize that the previous if statement and the else statement are meant to be connected.

What is better to use? Spaces or Tabs?

Mixing tabs and spaces is allowed (at least on my version of Python) but not recommended. Python assumes tabs are 8 characters long, which may not match your editor.

Just say “no” to tabs. Most editors allow them to be automatically replaced by spaces.

I’m still having a hard time with Python’s indentation syntax. What do I do?

Don’t get discouraged if you’re still struggling. It can take time to get use to Python’s whitespace syntax rules. Here are some tips to help:

  • Get an editor that will tell you when you have an indentation error. Some good ones as said above are, PyCharm, SublimeText, and Jupyter Notebook.
  • If you have an editor, see if it has an option to automatically convert tabs to spaces.
  • Just write code. That’s the single best way to get better. The more you write Python code, the better you’ll get. The only thing you need to make sure of is that if you hit any of the above errors then you should be able to fix it without a second thought.
  • If your code is really messy then this website might help.