What is Indentation in Python with Example

Indentation is one of the most significant features of Python. It refers to white spaces to denote the beginning of a block of code.

In other programming languages like Java, developers use indentation to keep their code neat and to enhance readability of code.

But Python use line indentation to define the block of code, which is rigidly enforced. A block of code defines the class definition, function definition, conditional statement, or loop.

Unlike other programming languages, Python does not use curly braces ({ }) around the blocks of statements. It uses indentation (white spaces) to express the block structure of a program.

In other words, the correct usage of white spaces creates blocks in Python. Indention makes Python programs look more organized and maintains readability of the code.

How to intend a block of code in Python?


While starting a block of codes, type the colon (:) symbol at the end of the first logical line and press enter. In the next line, create indentation by pressing white spaces (space or tabs) before you write the new line of statements.

A visual example of Python indentation is shown in the below figure.

An example of Line indentation in Python

Here are some important key points that you should know about indentation in Python. They are as:

1) All statements that are the equal distance from the right belong to the same block as shown in the above figure.

2) The first line of block always ends with a colon (:).

3) The number of spaces used in an indentation can vary, but for all statements in a particular block, the number of spaces should always be the identical.

4) If we use 2 space indentation, it means this is the part of code block 1.

5) If we use 4 space indentation, it means we just started code block 2. Again, if we are using 4 spaces, means, we are still in the code block 2.

6) On using 8 space indentation, we started code block 3.

7) As per Python community standard, developers generally use four spaces indentation for the first level, and eight spaces for nested block and so on.

8) All statements in the same block are called suites in Python and they are intended by the same spaces. If the indentation is not correct, it will throw an indentation error “Unexpected Indent”.

9) By default, Python uses four spaces of indentation.


Note: Whenever you choose the number of spaces, keep it consistent so you do not get confused and easy for you to have a look into the code and understand it better.

Correct Usage of Python Indentation Examples


1) Let’s take an example code snippet in which we will use two spaces of indentation. Just concentrate on the indentation part, do not bother to understand the program code at this stage.

Later, you will learn the function in Python, you will understand easily the program code.

# Declare a user-defined function.
def display():
# Below two lines of code are the part of the function.
  var = "Scientech Easy" # This statement is indented by two spaces.
  print(var) # this print statement is indented by two spaces.
# Below is the code to call a function named display().
display()
Output:
      Scientech Easy

In this example, you can see there are two lines of code that are intended by 2 spaces of indentation, which represents that those 2 lines of code are the part of function display().


2) Let’s take an example in which we will use 4 spaces of indentation in Python.

# Declare a user-defined function with parameter.
def display(parameter):
# Below three lines of code are the part of the function.
    var = "Hello" # This statement is indented by four spaces.
    print(var) # this print statement is indented by four spaces.
    print(var, parameter)
# Below is the code to call a function named display().
display("Python")
Output:
      Hello
      Hello Python

In this example, we have used four spaces of indentation to make the three lines of code as part of function.


3) Let’s take one more example based on the correct usage of indentation in Python.

name = 'Ivaan'
if name == 'Ivaan':
    print('WelCome Ivaan..') # Intended by four spaces by default.
    print('How are you, today?') # # Intended by four spaces by default.
else:
    print('Dude! whoever are you ') # Intended by four spaces by default.
    print('Why are you here?') # Intended by four spaces by default.

print('I am fine, thank you!')
print('Have a nice day!')
Output:
      WelCome Ivaan..
      How are you, today?
      I am fine, thank you!
      Have a nice day!

Explanation:

a) In the first statement, we have declared a variable name and assigned it a value “Ivaan”.

b) In the second line, the statement if name == ‘Ivaan’: is evaluated. Since it will return true, so interpreter executes the block (or body) of two statements inside the if statement. These two statements are indented by the usage of four spaces by default.

c) The two statements inside the block are print(‘WelCome Ivaan..’) and print(‘How are you, today?’) and they get executed by interpreter.

d) Once the block of statements gets executed, the else part is skipped and control of execution transfers to the next statement, which is print(‘Have a nice day!’), and is executed it.

e) In this example program, four spaces indented the statements inside the blocks of if-else by default.


4) Let’s take an example in which we will use two different blocks with two different sets of indentation.

def school(parameter):
  print(parameter) # indented by two spaces.

def city(parameter):
    print(parameter) # indented by four spaces by default.

# Calling methods.
school('RSVM')
city('Dhanbad')
Output:
      RSVM
      Dhanbad

In this example, we have declared two different methods that follow two different sets of indentation.

How to avoid indentation error in Python?


1) If you skip indentation and write the code as below, then you will get an indentation error. A below example code would throw IndentationError: expected an indented block error.

Wrong Indentation Error:

if(6 > 3):
print("6 is greater than 3") # Here, we have skipped indentation space before the print statement.

With Correct Indentation:

if(6 > 3):
    print("6 is greater than 3") # Here, we have indented with four spaces.
Output:
      6 is greater than 3

You can adjust the number of spaces, but must be at least single spaced. For example, you can execute the below code with higher indentation, but you must follow the same number of spaces for a specific set of code. Otherwise, you will receive an indentation error.

if(6 > 3):
          print("6 is greater than 3")

2) The number of white spaces should always be the same for all statements in a particular block. Else, Python will throw IndentationError: unexpected indent. Look at the following examples given below.

Mismatch Indentation:

a = 10
b = 20
c = 30
if(b > a):
  print("b is greater than a")
    print("b is greater than a but less than c")
Output:
      IndentationError: unexpected indent

In this example, Python will throw an “Unexpected Indent” error because the statement print(“b is greater than a”) has 2 spaces from the beginning whereas the statement print(“b is greater than a but less than c”) has four spaces from the beginning. Let’s see the correct usage of indentation.

Correct Indentation:

a = 10
b = 20
c = 30
if(b > a):
    print("b is greater than a")
    print("b is greater than a but less than c")
Output:
      b is greater than a
      b is greater than a but less than c

Let’s see another example of mismatch in the indentation.

Mismatch Indentation:

def display(parameter):
    institute = "Scientech Easy"
  print(institute)
    print(parameter)

# Calling a function.
display('Dhanbad')

In this example, Python will throw an “Unexpected Indent” error because city = ‘Dhanbad’ has four spaces from the beginning whereas print(city) has only two spaces of indentation.

Correct Indentation:

def display(parameter):
    institute = "Scientech Easy"
    print(institute)
    print(parameter)
# Calling a function.
display('Dhanbad')
Output:
       Scientech Easy
       Dhanbad

3) If you use indentation on the first line of code, Python will throw an “IndentationError: unexpected indent” error. Let’s take an example based on it.

Wrong Indentation:

 def display(): # Indentation in the first line of code.
    name = 'John'
    print(name)
# Calling a function.
display()
Output:
      def display():
      IndentationError: unexpected indent

Correct Usage of Indentation:

def display():
    name = 'John'
    print(name)
# Calling a function.
display()
Output:
      John

Rules of Python Indentation


There are the following rules of indentation in Python that you should keep in mind.

a) By default, Python uses four indentation spaces. However, the number of spaces can be variable and is up to the programmer. But we need a minimum of one space to indent a statement.

b) The first line of python code cannot have white space.

c) Indentation is compulsory in python to define the blocks of codes.

d) The number of white spaces must be the same in a block of code.

e) By convention, white spaces are more preferred instead of tabs to indent a block of code in Python.

Benefits of Indentation in Python


There are the following benefits of using indentation in Python. They are as:

1. The main reason of usage of indentation in Python is to identify the block structure. But it also makes Python programs look more organized and readable.

2. Indentation also helps to reduce the number of lines of code in Python.

3. In other programming languages such as C, C++, or Java, missing of curly braces ({ }) generates errors we can avoid it in Python.

Disadvantages of Indentation


You must carefully indent the block of code with the proper number of white spaces. If the number of lines of code is huge, sometimes, it can be a tedious task to maintain uniformity.


In this tutorial, we have covered about line indentation in Python, rules of indentation with unique examples, and its advantages and disadvantages. Hope that you will have understood the basic points of line indentation and practiced all example programs.
Thanks for reading!!!
Next ⇒ Comments in Python⇐ Prev Next ⇒

Please share your love