Python error unindent does not match any outer indentation level

How to Fix Indentation Error in Python: unindent does not match any outer indentation level, This type of error occurs when we assign extra indent to an identical code block, due to additional indent python compiler is not able to recognise similar code blocks, and it throws an error.

Indentation is important for making your code look well-structured and clean. This will help you to separate the code into multiple blocks and make it more readable. In languages such as C or C++, curly braces {} are used.

Improper indentation in Python raises an error called “unindent does not match any outer indentation level”. In this post, we will figure out the ways to solve this problem.

But first, let us learn about indentation in Python.      

What is Indentation in Python?

In Python, indentation is the space or tab that programmers put at the beginning of every line. In Python, whitespace is used for indenting the code. Code is indented from left to right.

In python, we don’t use indention just for the beautification of code or to make the code look pretty. When you do indent using one space or two space for the first line, it must be same for the rest of the lines. 

In the picture shown below, you can see there are three blocks of code, and each block code has an identical indentation. 

What is Indentation

What is ‘IndentationError: unindent does not match any outer indentation level’?

This type of error occurs when we assign extra indent to an identical code block. Due to this additional indent, the python compiler is not able to recognize similar code blocks, and it throws an error. To fix this, you have to make sure all blocks of similar code have the same indentation.

IndentationError: Unindent does not match any outer indentation level

Let us look at some examples to understand the error and its solution.

Example:

a = int(input("Please enter an integer A: "))
b = int(input("Please enter an integer B: "))
if b > a:
        print("B is greater than A")
elif a == b:
        print("A and B are equal")
    else:
        print("A is greater than B"

Output:

File "t.py", line 7
    else:
        ^
IndentationError: unindent does not match any outer indentation level

In the above code example “if” and “elif” statements are assigned with no indent whereas “else” statement (see line no 7) which is belong to “if” statement, assigned with an extra indent. Due to an additional indent python compiler was not able to recognize “else” statement (line no 7) and throw the indentation error ’unindent does not match any outer indentation level’.

Correct Code:

a = int(input("Please enter an integer A: "))
b = int(input("Please enter an integer B: "))
if b > a:
        print("B is greater than A")
elif a == b:
        print("A and B are equal")
else:
        print("A is greater than B")

Therefore, before compiling the code, check the overall indentation to avoid the “unindent does not match any outer indentation level” error. 

Python uses indentation to define the scope and extent of code blocks in constructs like class, function, conditional statements and loops. You can use both spaces and tabs to indent your code, and if you use both methods when writing your code, you will raise the error: IndentationError: unindent does not match any outer indentation level.

We will go through the error in detail and an example to learn how to solve it.


Table of contents

  • IndentationError: unindent does not match any outer indentation level
    • What is Indentation in Python?
  • Example: Mixing Indentation in Function
    • Solution
  • Summary

IndentationError: unindent does not match any outer indentation level

What is Indentation in Python?

Indentation is vital for constructing programs in Python. It refers to the correct use of white space to start a code block. With indentations, we can quickly identify the beginning and endpoint of any code block in our program. Let’s look at how indentation in Python works visually:

code indentation in Python
Code indentation in Python

To indicate a code block in Python, you must indent each block line by the same amount. You can use four spaces or one tab, a typical indentation for Python. According to the conventions in PEP 8, four white spaces is preferable. You can use indentation to nest code blocks within code blocks.

Python objects if you use both spaces and tabs to indent your code. You need to use one form of indentation, and this can be tricky because you cannot see the difference between spaces and tabs.

The error commonly occurs when you copy code from other sources to your script. The code you are copying may have a different indentation to what you are using.

The error can also occur if you have used indentation in the wrong place or have not used any indentation.

Example: Mixing Indentation in Function

Let’s write a program that calculates the square roots of a list of numbers and prints the result to the console. We will start by defining the function to calculate the square root of a number:

def get_square_roots(number_list):

    for number in number_list:

        sqrt_number = number ** 0.5

	    print(f'The square root of {number} is {sqrt_number}')

The function uses a for loop to iterate through every number in the list you will pass. We use the exponentiation operator to calculate the square root of the number and then print the result. Next, we will define the list of numbers and then call the get_square_roots() function.

number_list = [4, 9, 16, 25, 36]

get_square_roots(number_list)

Let’s run the code and see what happens:

sqrt_number = number ** 0.5
                          ^
IndentationError: unindent does not match any outer indentation level

The code returns the IndentationError, and the tick indicates the line responsible for the error.

Solution

We can use a text editor like Sublime Text to see the indentation style in our code by highlighting it, as shown below.

Code block with mixed indentation style
Code block with mixed indentation style

Each line represents a tab, and a dot represents a space. We can see a mix of spaces and tabs in the code snippet, particularly the line sqrt_number = number ** 0.5. To fix this, you can change replace the indentation on the other lines with four white spaces as this is the preferred indentation method. Alternatively, you can use tabs. Let’s look at the revised code in the text editor:

Code block with consistent indentation style
Code block with consistent indentation style

We can see each line has spaces instead of tabs. Let’s run the code to see what happens:

The square root of 4 is 2.0
The square root of 9 is 3.0
The square root of 16 is 4.0
The square root of 25 is 5.0
The square root of 36 is 6.0

The program returns the square root of each number in the list we pass to the function. You do not need to use a text editor to find differences in indentation style, but it does make it easier to spot them. Alternatively, you can manually go through each line in your code and stick to one indentation style.

Summary

Congratulations on reading to the end of this tutorial! The error “indentationerror: unindent does not match any outer indentation level” occurs when you mix spaces and tabs to indent your code. To solve this error, ensure all your code uses either spaces or tabs in your program. You can use a text editor to highlight your code to make it easier to spot the differences. Otherwise, you can go over the lines in your code and stick to one indentation style. To minimise the likelihood of this error, you can write your code in a text editor or Integrated Development Environment (IDE) like PyCharm, which automatically indent your code in a consistent style.

For further reading on Python code structure, go to the article: How to Solve Python UnboundLocalError: local variable referenced before assignment.

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

Indenting your code can be a messy business if you try to use both spaces and tabs. In Python, using both methods of indentation results in an error. This error is “indentationerror: unindent does not match any outer indentation level”.

In this guide, we talk about what this error means and when it is raised. We walk through an example of this error in action to help you learn how to fix it.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

indentationerror: unindent does not match any outer indentation level

Python code can be indented with tabs or spaces. It’s up to you.

Python only has an objection when you use both spaces and tabs to indent your code. Python requires you use only one method of indentation. This is because the language is statically typed. Statically typed programming languages are sticklers when it comes to syntax. 

Indentation errors are a difficult one to understand because it involves the invisible: mixing spaces and tabs. Depending on the code editor you are using, you may not even be able to see whether spaces or tabs have been used until you delete your indents from your code.

IndentationErrors are common when you copy code snippets from the internet. Every developer has their own preference when it comes to indentation and you’ll often find code snippets do not adhere to your own preferences. Some snippets will indent with spaces.

If a code snippet you copy into your program uses a different type of indentation, you may see an IndentationError in your code. This is because you mix tabs and spaces.

An Example Scenario

Write a program that finds the factors of a number.

Start by defining a function to calculate the factors of a number:

def get_factors(number):
	for i in range(1, number + 1):
		if number % i == 0:
			print("{} is a factor of {}.".format(i, number))

This function uses a for loop to iterate through every number in the range of 1 and the number we have specified plus 1.

In each iteration, our program checks if there is a remainder after dividing “number” by “i”. We do this using the modulo operator. If there is not a remainder, “i” is a factor of “number”.

If a number is a factor of “number”, a message is printed to the console.

We to call our function:

This code calculates all the factors of 32. Run our code and see what happens:

  File "test.py", line 4
	print("{} is a factor of {}.".format(i, number))
                                               	^
IndentationError: unindent does not match any outer indentation level

Our code returns an IndentationError.

The Solution

We have made a mistake with the styling of our code. We know this because IndentationErrors are raised when there is a problem with how your code is indented.

Take a look at how our code is styled. In Sublime Text, we can see the styles of our code by hovering over each line:

ZkT2zfCE1h22 Ldf RwNqSrZL9fUBLG VdcBcqh559l QY6dDanxnhIiihRf52m10qUKnPgFyT2uG6YxVF5MoRzAVitrOwbnF 04EUYhdD3dMZZXkO3aOERWcZYtYsJpOFu1rqun

Each line represents a tab. Each dot represents a space. You can see that we have mixed up both spaces and tabs in our code snippet. Python likes consistency in indents and so the interpreter returns an error when we run our code.

If you use a text editor that does not support this behavior, check whether your code uses spaces or tabs by backspacing your indentation. If your code removes a tab when you press the backspace key, that part of your code is using tabs.

Spaces are the preferred method of indentation in Python but you can use tabs if you want.

Let’s revise our code:

def get_factors(number):
		for i in range(1, number + 1):
				if number % i == 0:
						print("{} is a factor of {}.".format(i, number))

We have replaced all the spaces with tabs. Run our program again:

1 is a factor of 32.
2 is a factor of 32.
4 is a factor of 32.
8 is a factor of 32.
16 is a factor of 32.
32 is a factor of 32.

Our code successfully returns a list of all the factors of 32. This shows us that our code was logically accurate all along. It was our indentation that caused the problem.

Conclusion

The “indentationerror: unindent does not match any outer indentation level” error is raised when you use both spaces and tabs to indent your code.

To solve this error, check to make sure that all your code uses either spaces or tabs in a program. Now you’re ready to resolve this common Python error like a professional software developer!

In this post, we’ll provide 5+ fixes for the frustrating Indentation Error: unindent does not match any outer indentation level error.

One of the common errors in programming is the indentation error. It happens when unindent does not match any outer indentation level, but what is this error all about and how to fix it? Before we define what indentation is and why this error occurs, let us identify how programs work.

Each computer program has its own coding style guidelines. In programming, there is a set of standards used in writing the source code for a specific computer program. They are known as the code lay-out or the programming style. It helps the programmers read and understand a particular source code whose function is to prevent initiating errors.

And this error can really piss people off

WHAT THE ACTUAL F IT SHOULD WORK BUT NOOOO

«compile error: unindent does not match any outer indentation level»

AYOKO NA

— solanaceae (@lc_potato) September 27, 2017

In programming, code lay-out is designed for a specific programming language.

Programming languages are letters taken from the alphabet that is formed in accordance with a particular set of rules. This is where indentation comes in. Programming languages use indentation to determine the limits of logical blocks of code. If codes are indented, codes are more eye-friendly. In other words, they will be readable. On the other hand, the indentation in Python is required to indicate which blocks of code a statement belongs to.

Indentation uses four spaces per indentation level. This is where indentation error usually takes place. This is where unindent does not match any outer indentation level. Mixing spaces with tabs is what causes the error.

Also, other factors that affect the alignment of the elements may cause the system to respond differently. There are guidelines, fixes, and preventive measures for this issue below.

But first- check out some more reaction from social media regarding this annoying error: 

It also gives you a diagnostic error right when you run the code:

IndentationError: unindent does not match any outer indentation level.

— 🖥️🏳️‍🌈unsafe fn bot() ➡️ impl CRJ Shitposting (@KardOnIce) November 27, 2018

The most frustrating error for me in Python/ Spyder is «unindent does not match any outer indentation level». tab, space still not working….. I hate the error with passion #python #100DaysOfMLCode #ai #MachineLearning

— Oladeji Stephen (@RealSaintSteven) October 9, 2018

Understanding Python Indentation

The ICMEStudio YouTube channel shot a popular video clarifying how indentation works in Python:

How To Prevent The Indentation Error From Occuring?

The guidelines below are just the basic steps to follow in preventing indentation error occurs.

  • First, it is important to align the codes with an opening delimiter. By using Python’s implicit line linking inside brackets, braces, and parentheses, these continuation lines should align wrapped elements vertically. A hanging indent can be used as well.

Note: In using a hanging indent, no arguments must be placed on the very first line. Also, to clearly differentiate the continuation line, an additional indentation must be used.

  • Add four spaces to determine arguments from the rest. This will be considered as an extra level of indentation.
  • Add an additional indentation level for hanging indents.

Note: Remember that the 4-space rule is nonmandatory for hanging indents.

How To Fix It?

The number of indentation always matters. Having a missing or extra space could cause an unexpected behavior that we consider the error. Within the similar block of code, statements should be intended at the same indentation level. So, here are preferred methods to fix the error.

Fix 1

For those who use Sublime Text as their source code editor, follow these steps:

  1. Set Sublime Text to use tabs for indentation.
  • Go to view
  • Choose indentation
  • Convert Indentation to Tabs.
  1. Go to the sub-menu and look for the ‘Indent Using Spaces’ option and uncheck it.

This will automatically resolve the issue.

Note: Injecting copy-pasted code could be a source of the problem. So, avoid doing it. Space and tab problems can be prevented if you will display invisible characters within your text editor. It will quickly resolve indentation-related errors.

Also, you can avoid the issue by using the package Anaconda. Try following these steps:

  1. Install Anaconda.
  2. Open your sublime file.
  3. Look for ‘Open Spaces’ and right click.
  4. Choose Anaconda.
  5. Click on auto format.
  6. Click Done or Press CTRL+ALT+R

Video Guide: Sublime Text Line and Indentation Tools

Fix 2

For Python’s IDLE editor users, follow the steps below, if it suggests one similar message:

1) Choose All, e.g. Ctrl + A

2) Select Format -> Untabify Region

3) Double check if your indenting is still correct, then save and rerun the program.

This works well for Python 2.5.4 and Python 3.4.2

Note: Make sure not to mix space with the tab because Python is whitespace sensitive.

Fix 3

For Vim users, follow these steps and it will indent everything. It will also clear up any space you threw in.

  1. Hit escape.
  2. Type gg=G

Fix 4

For ATOM users, you can do these steps to resolve the error:

  1. Go to Packages.
  2. Choose Whitespace.
  3. Convert Spaces to Tabs.
  4. Check your file indentation:

python -m tabnanny yourFile.py

or

>python

>>> help(“yourFile.py”)

And here’s another way to resolve the issue. This method also works for ATOM users.

  1. Go to Packages.
  2. Choose Whitespace.
  3. Remove trailing whitespaces.

Fix 5

For indentation-related issues in Notepad++, you can fix the problem by doing this:

  • For unexpected indentation:
  1. Go to the Search tab.
  2. Tap on replacing.
  3. Hit the radio button EXTENDED below.
  4. Replace t with four spaces.
  • For Outer indentation Level:
  1. Go to.
  2. Search tab.
  3. Tap on replacing.
  4. Hit the radio button EXTENDED below.
  5. Replace n with nothing.

Video Guide: How To Indent HTML Tags In Notepad++

Fix 5

For Spyder users, look carefully at your ‘if statement’ and make sure that all if, elif and else statements have exactly the same spacing as if they are in the same line.

Use the reference below:

def your_choice(answer):

if answer>5:

print(“You’re overaged”)

elif answer<=5 and answer>1:

print(“Welcome to the toddler’s club!”)

else:

print(“No worries mate!”)

Forum Feedback

To understand more about IndentationError: unindent does not match any outer indentation level, we search through several Python message boards and support forums.

python IndentationError unindent does not match any outer indentation level

In general, users wanted information about IndentationError: unindent does not match any outer indentation level Vim/ ATOM/Jupyter/Notepad C++. They also wanted to know about how to handle IndentationError: unindent does not match any outer indentation level in Django and Pycharm.

A Python novice shared that he completed his code, and he was certain that he has programmed it correctly.

  • However, he was getting an error that he didn’t know the meaning of.
  • It said, “IndentationError: unindent does not match any outer indentation level.”
  • So, he reached to the programming community for advice.
  • They said that the most probable cause for such an error would be that he had mixed tabs with spaces which resulted in the wrong indentation.
  • What they recommend was to search for tabs and then replaces the tabs with spaces.

Another user also ran into the same error. Following advice from other Python programmers, he looked at what tabs and spaces he had used. He discovered that his first line was spaced, but he had used tabs for the rest of the code. He was surprised by that because he didn’t know that tabs and spaces mattered in Python.

An individual remarked that it could be tricky to remember how to use tabs and space properly in Python. That’s why he recommended that you use the right text redactor to edit your Python code and mentioned that you could configure it to replace tabs with spaces so that you could avoid IndentationError: unindent does not match any outer indentation level errors.

python 3.4 3 unindent does not match any outer indentation level error http://t.co/vkXNJs9fb8 http://t.co/SgsIGGpwz7 #Python via @dv_geek

— Python Questions (@Python_Quest) June 25, 2015

Another poster also mentioned that spaces are preferred in Python and that you can employ SublimeText because it shows spaces as dots. In this way, you can quickly find out where you’ve used tabs and fix it on the spot.

A poster explains that if you have used a tab somewhere instead of a space, you can change it quickly in Sublime. Simply go to View –> Indentation –> Convert Indentation to Tabs. He also recommends that you uncheck “Indent Using Spaces” in the same menu so that you don’t make an accidental mistake.

A Python user says that if you’re using ATOM, you also have the option to convert tabs to spaces when you get the indentation error. He explains that you must click on Packages > Whitespace > Convert Spaces to Tabs, and you’re ready to go.

Another forum member comments when you get IndentationError: unindent does not match any outer indentation level errors you can check for problems using “python -m tabnanny yourfile.py”. However, several users who have tried that solution said that they didn’t get any output and one poster complained that it showed an error in the wrong line.

my first python error…. IndentationError: unindent does not match any outer indentation level

— Hruhiko Soma (@harupiko) September 6, 2007

A Python expert explains that it’s true that spaces are preferred according to the Python style guide. However, as long as you use only spaces or only tabs you shouldn’t get indentation errors, but using both will cause a conflict.

Another user explains that besides mixing tabs and spaces in code, other sources of indentation problem will arise if you copy and paste code lines. He also suggests that you always display invisible characters like spaces/tabs in your editor so that you can spot a mismatch.

A forum commentator shares that his problem with IndentationError: unindent does not match any outer indentation level came from an incorrect configuration of PyDeck. That’s why he advises that you check the settings to make sure that they are the correct one. He observes that Python is very strict with how you should structure your code and that you should read the style guide again if you’re not sure which rules apply to Python.

Another poster states that you should rely on a good Python IDE if you’re serious about programming. He points about that an IDE can identify and highlight wrong indentations so that you don’t have to wonder what’s wrong with the code.

A beginner programmer said that he followed the advice of fellow Python users and that he replaced tabs with spaces. However, he still kept getting the same indentation error. It turned out that his indentation wasn’t consistent. He didn’t know that he should stick to four spaces per level of indentation, which is the recommended number.

Summing Up

Coding is a crucial and sensitive task. This is why programmers need to be extra careful in inserting program languages. In resolving issues like the indentation error, different approaches could be used to resolve the problem.

Also, there are things you need to know ahead. First, check the source code editor you are using because different procedure applies. Follow the correct settings and know the possible causes that may trigger the system to behave differently.

Also, you can rely on forums online and video tutorials since people around the world encounter the same issues as yours and might be able to share how they resolve it their way. Be knowledgeable and resourceful enough to gather more information as solutions may vary because of the system compatibility.

And lastly, don’t hesitate to share what works for you because it could also save someone on the other side.

Ryan is a computer enthusiast who has a knack for fixing difficult and technical software problems. Whether you’re having issues with Windows, Safari, Chrome or even an HP printer, Ryan helps out by figuring out easy solutions to common error codes.

Cover image for About "Unindent does not match any outer indentation level" error in Python

Reza Lavarian

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

The “IndentationError: unindent does not match any outer indentation level” error occurs when the indentation of a line doesn’t match up with the expected indentation level of the current code block. On the other hand,

File /var/www/sandbox/test.py, line 4
  print(word)
        ^
IndentationError: unindent does not match any outer indentation level

Enter fullscreen mode

Exit fullscreen mode

In the above error message, Python complains about line 4, where the code is indented differently than what Python expects.

Copy/pasting code snippets from the Internet or another editor is the common can lead to improper indentation.

Since the error message shows the exact location, the solution is just re-indenting the affected lines.

In this quick guide, I’ll explain why this error happens and how indentation in Python works.

We’ll finish the guide by learning tips on fixing indentation-related issues on three popular code editors.

Indentation in Python Explained

In Python, indentation isn’t a style choice; It’s a part of the syntax and is required by Python flow-control features such as if statements, loops, classes, and functions.

Python uses the whitespaces at the beginning of a line to compute the indentation level of that line; It’s how Python figures out to which block the statement belongs.

For instance, it’ll know which statements are inside the loop to be repeated.

word = 'example'
for letter in word:
    print(letter)
 print(word)

Enter fullscreen mode

Exit fullscreen mode

In the above example, Python considers the first print statement to be inside the loop and the second print statement to be outside.

Now, let’s see when this indentation code occurs?

In the above example, if you indent the second print by a couple of whitespaces, you’d make an ambiguous situation for Python to determine the indentation level of our loop.

Python expects the line following an indentation level (e.g., for) to be less indented. However, in our example, the second print statement is slightly indented to the right. This makes it the determining line for Python to compute the indentation level for our for loop.

And since the first print statement is now indented differently than the determining line, Python throws the indentation error.

word = 'example'
for letter in word:
    print(letter)
 print(word)

Enter fullscreen mode

Exit fullscreen mode

Another example would be an if/else statement:

if a==1:
    print('test')
 else:
    print('test2')

Enter fullscreen mode

Exit fullscreen mode

In the above code, else is slightly indented to the right. And since Python expects it to be at the same level as if, it throws the indentation error.

As a rule of thumb, statements ending with a colon (:) require the following line to be indented (a new indentation block).

The relevant statements are:

  • class
  • def (functions)
  • if, elif, and else
  • for and while
  • try, except, and finally
  • with
  • match and case (Python 3)

Evil tabs!

Sometimes all lines look perfectly aligned, but you still get the error. That usually happens when you copy a tab-indented code from the Internet:

A python block with is using tabs and spaces for indentation
You usually won’t have to worry about it because most modern editors automatically convert tabs to spaces (or vice versa if configured accordingly).

However, if you copy/paste a code snippet from the Internet (e.g., Stackoverflow), you’ll have to re-indent them manually.

To avoid this situation, you can make all whitespaces visible in your code editor. This will give you a quick way to prevent (or debug) indentation-related mistakes.

Additionally, you can use Python’s tabnanny module to help you detect indentation errors quickly. Tabnanny checks for consistency in the indentation of code blocks in a Python code. If such an error is detected, it will throw the indentation error.

dwd@dwd-sandbox:~$ python3 -m tabnanny test.py 
'test.py': Indentation Error: unindent does not match any outer indentation level (<tokenize>, line 4)

Enter fullscreen mode

Exit fullscreen mode

How to fix unindent does not match any outer indentation level error

As mentioned earlier, you can fix this indentation error by ensuring that the indentation of the code block matches the expected indentation level.

But there are also automatic ways to do so. That’s actually the preferred method among Python developers. Let me share with you some indentation tips & tricks on three popular code editors:

  • Visual Studio Code
  • Sublime Text
  • Vim

Visual Studio Code: Firstly, to make whitespace characters (space or tab) visible in VS code, open up the command palette by pressing ⌘+Shift+P (on Mac) or Ctrl+Shift+P (on Windows), type, Toggle Render Whitespaces and hit enter (↵)

As a result, whitespaces are displayed as gray dots and tabs as tiny arrows. Having whitespaces visible enables you to spot inconsistencies as your write code — even if they look fine.

And to fix the possible tab/space inconsistencies, open up the command pallet again, and run Convert Indentation to Spaces or Convert Indentation to Tabs — depending on what character you use for indentation.

Sublime Text: If you have a space/tab indentation issue on Sublime Text, go to View -> Indentation and select Indent Using Spaces.

And to see the whitespace characters, highlight your code (Ctrl + A), and you should be able to see any possible inconsistency.

Vim: Like the other editors, Vim automatically converts any whitespace to space characters. However, if you’ve copied some tab-indented code from elsewhere, you can use Vim’s :retab command to convert them into spaces quickly.

You can make whitespace characters visible with set list and set listchars commands.

First, run this in Vim:

:set list

Enter fullscreen mode

Exit fullscreen mode

And then run:

:set listchars=space:␣,tab:-> 

Enter fullscreen mode

Exit fullscreen mode

You can replace and -> with the characters of your choice.

A note on Tabs and space characters in Python indentation
In Python, tabs and spaces are interchangeable when it comes to indentation.

However, the Python style guide (PEP 8) recommends using spaces over tabs — four space characters per indentation level.

According to PEP 8, if you’re working with a code that’s already using tabs, you can continue using them to keep the indentation consistent.

Additionally, Python disallows mixing tabs and spaces for indentation. So you can’t use tabs and space characters in the same indentation level — Just like the above examples.

Alright, I think that does it! I hope you found this quick guide helpful.

Thanks for reading.


❤️ You might like:

  • AttributeError: ‘str’ object has no attribute ‘decode’ (Fixed)
  • How a computer program works
  • How back-end web frameworks work?
  • Your master sword: a programming language

When I run my python script code, I meet an error like this IndentationError: unindent does not match any outer indentation level. This error is so strange and hard to find the reason. After some investigation, I finally find the solution.

1. Why IndentationError.

Indentationerror error is always because of tab and white space mixed in your python code. We generally use 4 white spaces to present indentation in python. But as a coder, we may sometimes use the tab key to present the indentation. So if you mix used white space and tab for indentation, this error may occur.

2. How To Locate Indentation Error.

When you run your python code, if the code has an indentation error, it will throw the error message out to you which will make you struggled. The error message will tell you which line of code has an indentation error.

C:WorkSpace>test_sys_arg.py
  File "C:WorkSpacetest_sys_arg.py", line 11
    print('argv ' + str(i) + ' = ' + tmp_argv)
                                             ^
IndentationError: unindent does not match any outer indentation level

But you can also run the python command python -m tabnanny test_sys_arg.py to know which line of code has an indentation error.

C:WorkSpace>python -m tabnanny test_sys_arg.py
'test_sys_arg.py': Indentation Error: unindent does not match any outer indentation level (<tokenize>, line 11)

3. How To Fix Python IndentationError.

We all know one tab contains four white spaces, so we need to know where we use four white spaces to replace one tab in python source code. Please follow the below steps.

  1. Open your python source file use one text editor like Sublime Text.
  2. Then press Ctrl + A to select all python source code in the editor, then you can see at the beginning of line 11, there are four white spaces ( four dots) that should be replaced with one tab.
    see-python-indentation-use-tab-or-white-space-in-sublime-text
  3. Replace the four white space with one tab at the beginning of line 11, save the file and run it again, you will find the error has been fixed.
  4. There is also a shortcut in Sublime text which can help you to make conversion between tab to spaces.
  5. Click the View —> Indentation menu item in Sublime text, then it will list some sub-menu items.
  6. Click the Convert Indentation to Spaces or Convert Indentation to Tabs menu item can do the tab and spaces conversion.
  7. You can also specify to use white spaces for indentation by checking the Indent Using Spaces submenu item.
  8. Or you can select how many spaces that one tab will contain by choosing different Tab Width values.

Понравилась статья? Поделить с друзьями:
  • Python error loading mysqldb module
  • Python error list index out of range
  • Python error get traceback
  • Pycharm ошибка no module named
  • Python error fix