Indentation in Python (With Examples)

Indentation In Python

Indentation in Python is used to create a group of statements that are executed as a block. Many popular languages such as C, and Java uses braces ({ }) to define a block of code, and Python uses indentation.

To write bug-free, user-friendly and beautiful code, it is important to know many things about indentation, like its rules, its benefits, the error you get, etc. All of which we have covered in this tutorial. Let’s start with an introduction to indentation.

What is Indentation in Python?

Indentation in Python refers to the whitespaces at the start of the line to indicate a block of code. We can create an indentation using space or tabs.  When writing Python code, we have to define a group of statements for functions and loops. This is done by properly indenting the statements for that block.

The leading whitespaces (space and tabs) at the start of a line are used to determine the indentation level of the line. We have to increase the indent level to group the statements for that code block. Similarly, reduce the indentation to close the grouping.

The four whitespaces or a single tab character at the beginning of a code line are used to create or increase the indentation level. 

Let’s look at an example to understand the code indentation and grouping of statements.

def foo():
    print("Hi")

    if True:
        print("true")
    else:
        print("false")

print("Done")
Python Indentation
Python Indentation

Note: In Python programming languages the indentation in code can be done by using two spaces or four spaces (or any other number of spaces), you just have to be consistent, although 4 spaces for each level of indentation is the best practice.

Python Indentation Rules

Below are the rules that one should follow while using indentation:

  • The first line of Python code can’t have an indentation, it will throw IndentationError.
  • You should avoid mixing tabs and whitespaces to create an indentation. It’s because text editors in Non-Unix systems behave differently and mixing them can cause the wrong indentation.
  • It is preferred to use whitespace than the tab character.
  • The best practice is to use 4 whitespaces for the first indentation and then keep adding additional 4 whitespaces to increase the indentation.

Benefits of Indentation in Python

The proper use of indentation in a program provides many benefits, some of them are: 

  • Indentation is important to increase the readability of the code by clearly indicating the hierarchy (i.e. if statements belong to the same block or not).
  • This avoids the need to use delimiters such as braces or brackets, which is mandatory in most programming languages like C, C++, Java, etc.
  • Python indentation is consistent throughout the program, making it easier to debug.
  • In most programming languages, indentation makes the structure of the code proper. Python uses it for grouping, making the code automatically beautiful.
  • Python indentation rules are very simple. Most of the Python IDEs automatically indent the code for you, so it’s very easy to write the properly indented code.

Disadvantages of Indentation in Python

There are only a few disadvantages of indentation in code, let’s look at them:

  • Since whitespaces are used for indentation, if the code is large and indentation is corrupted then it’s really tedious to fix it. It happens mostly by copying the code from online sources, Word documents, or PDF files.
  • Most of the popular programming languages use braces for indentation, so anybody coming from a different programming world finds it hard at first to adjust to the idea of using whitespaces for indentation

Indentation in Python for loop

We have to increase the indentation in the for loop so that the code will be grouped together. Let’s look at an example of indentation in Python for loop.

def print_numbers(x, y):
    for i in range(x, y):
        print(i)

IndentationError Examples

Let’s look at some examples of the indentation error in Python.

Example 1:

>>>     x = 10
  File "<stdin>", line 1
    x = 10
    ^
IndentationError: unexpected indent
>>> 

We can’t have an indentation in the first line of the code. That’s why the Python interpreter throws IndentationError.

Example 2:

if True:
    print("true")
     print("Hi")
else:
    print("false")

Output:

Python IndentationError
Python IndentationError

The code lines inside the if block has different indentation level, hence the IndentationError.

Example 3:

if True:
    print("true")
else:
    print("false")

 print("Done")

Output:

Python Indentation Level Error Unindent
Python Indentation Level Error Unindent

Here the last print statement has some indentation but there is no statement to attach it, hence the indentation error is thrown.

Example 4:

if True:
print("true")
else:
print("false")

Output:

File "/Users/pankaj/Documents/PycharmProjects/PythonTutorialPro/hello-world/indent.py", line 2
    print("true")
        ^
IndentationError: expected an indented block

The print statements inside the if & else block must be indented.

Summary

Indentation refers to adding the relevant number of tabs and spaces at the beginning of lines of code to indicate a block of code in Python. Indentation in Python is very important to make the code readable, without indentation you find it hard to read or debug a program.

Indenting the Python code results in the habit of writing beautiful code all the time because it’s not a good-to-have feature but a must-have requirement of the code. To indicate a block of code in Python, you must indent each line of the block by the same whitespace otherwise you will get an indentation error.

Now you have enough knowledge to use indentation in Python, don’t forget to apply above mentioned rule, or else you will end up getting errors.

What’s Next?

References