Summary: The error IndentationError: unindent does not match any outer indentation level
arises if you use inconsistent indentation of tabs or whitespaces for indented code blocks such as the if
block and the for
loop. For example, Python will throw an indentation error, if you use a for
loop with four whitespace characters indentation for the first line, and one tab character indentation of the second line of the loop body. To fix the error, use the same number of empty whitespaces for all indented code blocks.
IndentationError: unindent does not match any outer indentation level
You must have come across this stupid bug at some point of time while coding. Isn’t it really frustrating to get an error even if your code is logically correct!
But after you read this article, you will probably never come across this error again. Even if you do, you will be able to rectify it in a flash! So without further delay let us dive into our discussion on IndentationError in Python.
Indentation in Python
Indentation refers to the spaces at the beginning of a line of code.
In other programming languages like Java, indentation simply serves the purpose of readability, i.e., even if you do not follow the proper indentation in such languages, it won’t hamper the execution of your code since they use braces {} to represent a block of code.
In Python indentation is an integral feature that represents a block of code and determines the execution of your code. When you skip proper indentation, Python will throw an IndentationError
.
Each line of code within a block should have an equal number of whitespaces before them. This means if a for
loop block contains two lines of code then each line should have four whitespaces (ideally) before them. If one line of code has three whitespaces while the other has four, you will again get an IndentationError
.
Example 1
Given a list containing marks. Based on given conditions the following program aims to divide each number within the list into a certain grade.
marks = [95,75,65,45,30] for k in marks: if k>=90: print(k,' = grade A') elif k>=75 and k<90: print(k,' = grade B') elif k>=55 and k<75: print(k,' = grade C') elif k>=45 and k<55: print(k," = grade D") else: print(k," - FAIL!")
Output:
File "D:/PycharmProjects/PythonErrors/rough.py", line 11 else: ^ IndentationError: unindent does not match any outer indentation level
In the above example, the error occurred in the else
statement because it does not follow the correct indentation.
? How to Fix “IndentationError: unindent does not match any outer indentation level“
➥ To fix IndentationError: unindent does not match any outer indentation level use the same number of whitespaces for each line of code in a given block.
Let us try and fix the error in our example scenario given above. You simply, have to provide proper spacing before the else statement such that it complies with the entire if-elif-else blocks
within the for loop
.
Solution:
marks = [95, 75, 65, 45, 30] for k in marks: if k >= 90: print(k, ' = grade A') elif k >= 75 and k < 90: print(k, ' = grade B') elif k >= 55 and k < 75: print(k, ' = grade C') elif k >= 45 and k < 55: print(k, " = grade D") else: print(k, " - FAIL!")
Output:
95 = grade A 75 = grade B 65 = grade C 45 = grade D 30 - FAIL!
✍️ Note:
- Generally, you should use four whitespaces for indentation and this is preferred over tabs.
- You can ignore indentation in line continuation, but it’s always recommended to indent your code for better readability.
- For example: if True :print(“Welcome To Finxter!”)
Let’s have a look at another example to ensure that you have a clear idea about the reason behind the occurrence of such an error.
Example 2
The following program is used to find the factorial of a number entered by the user.
def Factorial(n): # return factorial result = 1 for i in range(1, n): result = result * i print("factorial is ", result) return result num = int(input("Enter a number: ")) print(Factorial(num))
Output:
File "D:/PycharmProjects/PythonErrors/rough.py", line 6 return result ^ IndentationError: unindent does not match any outer indentation level
Explanation:
The above error occurred because of line 6 which indicates that the return statement
has an improper indentation. This happened because we mixed TAB and spaces in our code to indent the block of code within the function.
Solution:
To avoid this error, you can either use TAB or 4 whitespaces (recommended) before each line inside the function. Please note that the block within the for loop should have 8 white-spaces.
def Factorial(n): # return factorial result = 1 for i in range(1, n): result = result * i print("factorial is ", result) return result num = int(input("Enter a number: ")) print(Factorial(num))
Output:
Enter a number: 5 factorial is 24 24
? Avoid or Fix IndentationError In Code Editors
From the above examples it is evident that the major reason behind IndentationError in Python is the improper use of whitespaces and tabs in your program. In most code editors you can fix the number of whitespace characters/ tabs by setting the indentation levels.
Let us have a look at the settings in various code editors that allow us to auto-indent our code or fix the pre-existing errors :
? Sublime Text
- Click on View.
- Select Indentation.
- Select Indentation to tabs.
- Uncheck the Indent Using Spaces option in the sub-menu above.
? Notepad ++
Follow the settings given below to view the tabs or whitespaces in Notepad++ .
- Click on View
- Select Show Symbol
- Make sure that Show Whitespace and TAB and Show Indent Guide options are checked.
? Using an IDE
The advantage of using an IDE like PyCharm is that you do not have to worry about indentations in your code manually as this is taken care of by the IDE itself as show in the presentation given below.
Conclusion
I hope you enjoyed reading this article and learned how to fix Indentation Errors in Python. Please subscribe and stay tuned for more interesting articles in the future!
? Read More: Python IndentationError: unexpected indent (How to Fix This Stupid Bug)
- Do you want to master the most popular Python IDE fast?
- This course will take you from beginner to expert in PyCharm in ~90 minutes.
- For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.
Join the PyCharm Masterclass now, and master PyCharm by tomorrow!
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.