Home / Blog / Data Science / Indentation Error: Unindent Does Not Match Any Outer Indentation Level

Indentation Error: Unindent Does Not Match Any Outer Indentation Level

  • July 06, 2023
  • 9463
  • 20
Author Images

Meet the Author : Mr. Bharani Kumar

Bharani Kumar Depuru is a well known IT personality from Hyderabad. He is the Founder and Director of Innodatatics Pvt Ltd and 360DigiTMG. Bharani Kumar is an IIT and ISB alumni with more than 18+ years of experience, he held prominent positions in the IT elites like HSBC, ITC Infotech, Infosys, and Deloitte. He is a prevalent IT consultant specializing in Industrial Revolution 4.0 implementation, Data Analytics practice setup, Artificial Intelligence, Big Data Analytics, Industrial IoT, Business Intelligence and Business Management. Bharani Kumar is also the chief trainer at 360DigiTMG with more than Ten years of experience and has been making the IT transition journey easy for his students. 360DigiTMG is at the forefront of delivering quality education, thereby bridging the gap between academia and industry.

Read More >

Hello everyone! In this blog post, I'll talk about the “Indentation Error” in the Python programming language, providing a clear explanation, helpful examples, and fixes.

This is where my inspiration for writing this blog stems from. During the break, my content writer and I were talking about our jobs, obstacles, etc. Our chats went like this:

Nikhil: Ooff!!! I am so stressed; I want a strong coffee

Bindu: Oh! What happened to you?

Nikhil: Being a programmer, I am writing a coding from so long time! Worn-out

Bindu: hmm, Is it? but it should not be as stressed as my job

Nikhil: What???

Bindu: Yes, I need to be more focused on content, words, punctuation, and spaces to be taken care but your job is to just write code for the logic right?

Nikhil: No, even in programming there is a structure to write it and here also we need to take care of spaces which are so-called Indentation!

Bindu: Is it?

Nikhil: Yes. If the indentation is not in the right order an error will pop up that’s called “Indentation Error”

Let’s understand What is indentation error in more detail with examples!

What is Indentation?

An indentation is nothing more than blank space between lines of code that describes the organisation and operation of the specified code. The major purpose of the indentations is to denote the subordination of one feature to another. The "Tab" key in the Python programming language will enable us to indent each function with the appropriate amount of spaces.

Click here to learn Data Science Courses in Bangalore

Click here to explore 360DigiTMG.

What is Indentation Error?

We receive an error known as a "Indentation Error" when we don't provide enough spaces to suborder the code structure.

In Python, the error often looks like this:

Indentation Error: No outside indentation level matches unindent.

In Python, this issue typically results from uneven indentation. To create a function or loop, several programming languages employ the operator "." However, Python substitutes indentation (blank spaces) for. Therefore, there shouldn't be any indentation errors. When we copy and paste code, this problem occurs rather frequently.

Let's examine the indentation mistake in more depth using samples from Python:

Let’s understand the Indentation error with Python examples in detail:

Examples:

Example 1:

                 import sys

                def Factorial(n): # Return factorial
                    result = 1
                    for i in range (1,n):
                       result = result * i
                    print("factorial is ",result)
                return result

                Factorial(4)

Output:

File " ", line 7

    print("factorial is ",result)

IndentationError: unindent does not match any outer indentation level

# The above error arouses because there is some mismatch that occurred in the indentation.

REMEDY

Please be sure to properly check for any indentation errors. An order should be maintained for all indents. If we look at the aforementioned example, the "print" statement broke the rules about indentation.

Click here to learn Data Science Course in Hyderabad

Solution:

      import sys

       def Factorial(n): # Return factorial
           result = 1
             for i in range (1,n):
                 result = result * i
               print("factorial is ",result)
            return result

         Factorial(4)

Output:
factorial is 6
6

Example 2:

class junk:
           """docstring is indented too much"""
             def greet(self):
             return 'hello'

            s=junk()
            s.greet()

Output:

File " ", line 3

    def greet(self):

IndentationError: unindent does not match any outer indentation level.

Hint: As you see, the docstring which is used to describe any object, is not indented properly. This would cause a problem.

REMEDY

The docstring's indentation has to be fixed. By pressing enter after the: in the class declaration, you may correct this. The cursor for the appropriate indentation will automatically appear. As a result, modify the docstring's indentation as necessary.

Solution:
class junk:
          """docstring is indented too much"""
             def greet(self):
            return 'hello'

           s=junk()
          s.greet()

Output:
'hello'

Example 3:

          for i in range(10):
          if i%2==0:
          print('even numbers are\n')
          print(i)

Output:

File " ", line 4

    print(i)

IndentationError: unindent does not match any outer indentation level.

Hint: In the above example there are unequal blank places(indents) inside the “if block” which is causing the problem.

REMEDY

With indentation, exercise extreme caution. Statements in the try and except block should start off in the same place. The differences will be indicated in red in the Jupiter Notebook. We are able to check and amend them.

Solution:
           for i in range(10):
             if i%2==0:
             print('even numbers are\n')
             print(i)

Output:

even numbers are
0

even numbers are
2

even numbers are
4

even numbers are
6

even numbers are
8

Example 4:

import sys
           a=5
      try:
          rec=1/a
          print('reciprocal of given number is',rec)
except:
          print('reciprocal cannot be found')
          print('type of error is',sys.exc_info()[0])

Output:

File " ", line 5

    print('reciprocal of given number is',rec)

IndentationError: unindent does not match any outer indentation level

Hint: As seen in previous examples, the main problem lies with unequal indents. Here “ in try and except blocks” the unequal indentation is causing the problem.

REMEDY

The x [1] +=3 statement is indented here using the 'tab' key, while the return statement is indented using'spaces'. Please be aware that tab and space are not equivalent. So, for the indentation, please use either a tab or a space, not both.

Solution:

           import sys
            a=5
             try:
                 rec=1/a
                 print('reciprocal of given number is',rec)
       except:
                 print('reciprocal cannot be found')
                 print('type of error is',sys.exc_info()[0])

Output:

reciprocal of the given number is 0.2

Watch Free Videos on Youtube

Example 5:

When we use text editors to write the code, sometimes it is hard to find out the error.

            n = [5,55,555]
           def myFun(x):
                x[1]+= 5           #tab for indentation
               return x           #space for indentation
           print (myFun(n))

Output:

File " ", line 4

    return  x #space for indentation

IndentationError: unindent does not match any outer indentation level.

Hint: Here we used Sublime text editor to write the code. When we observed in Sublime, it seems like x[1].. and return is in the same order. But the problem persists.

REMEDIES

Here we are using 'tab' for the indentation of x[1]+=3 statement and 'spaces' to get the indentation of the return statement. Please note that tab and space are not interchangeable. So please use either tab or space for the indentation, not both.

  • In Sublime, If we select the code, then we can distinguish tab and space indentations easily OR
  • In Sublime toolbar, View - Indentation - Convert Indentation to Spaces OR
  • In Sublime toolbar, View - Indentation - Convert Indentation to Tabs

Solution:
        n = [5,55,555]
            def myFun(x):
           x[1]+= 5
           return x
       print (myFun(n))

Output:

        [5, 60, 555]

Click here to learn Data Science Course, Data Science Course in Hyderabad, Data Science Course in Bangalore

Data Science Placement Success Story

Data Science Training Institutes in Other Locations

Data Analyst Courses in Other Locations

Navigate to Address

360DigiTMG - Data Analytics, Data Science Course Training Hyderabad

2-56/2/19, 3rd floor, Vijaya Towers, near Meridian School, Ayyappa Society Rd, Madhapur, Hyderabad, Telangana 500081

099899 94319

Get Direction: Data Science Course

Read
Success Stories
Make an Enquiry