Indentation error python что это

Check out this article to understand how Python uses indentation to determine the beginning and end of code blocks and learn everything you need to know about Indentation Error in Python and their causes.

Home > Data Science > Indentation Error in Python: Causes, How to Solve, Benefits

As an interpreted, high-level and general-purpose programming language, Python increasingly garners accolades as the programming world’s most promising, leading and emerging platforms. Python is nothing without its ingenious design philosophy.

A key characteristic is an emphasis drawn to the notable use of significant indentation to enhance code-readability. The illustration highlighted below briefly outlines Python’s design philosophy’s bulwarks as twenty aphorisms, alluded to by Tim Peters, long-term Pythoneer, who eventually became one of Python’s most prolific and tenacious core developers. 

A Brief Introduction to Python

Before we delve into the specific technicalities underlying the indentation error in Python, we must get acquainted with Python’s fundamentals and the need for indentation. Doing so will not only help you gain a better appreciation of the error itself but offer an insight into the advantages that programmers gain by effectively choosing to resolve the same.

The inception of Python as a multi-paradigm programming language can be traced back to the year 1991. Since then, programmers have continually adapted Python’s core wireframe to suit a range of user-specific needs, such as data science and web and mobile development. 

Now, we all know that attempting to comprehend illegible handwriting is painstakingly tricky and often infuriating. Similarly, an unreadable and unstructured code is plain and simple, unacceptable in the programming world. This is where the notion of PEP or Python Enhancement Proposal comes to the programmer’s rescue. PEP to the Python Community is akin to a shared Google Doc for the general populace.

It is a continually updated descriptive mandate that keeps the Python programming community comprehensively informed of features and updates to improve code readability. By Guido van Rossum, Barry Warsaw and Nick Coghlan in 2001, the PEP 8 is referred to as Python’s style code. 

Our learners also read – python online course free!

What is Indentation?

It is primarily known that Python is a procedural language, and therefore, an indentation in Python is used to segregate a singular code into identifiable groups of functionally similar statements. The majority of the programming languages, including C, C++ and JAVA, employ curly braces’ {}’ to define a code block. Python marks a deviation from this design and prefers the use of indentation. 

Syntax of Indentation

According to the conventions outlined by PEP 8 whitespace ethics, every new iteration (i.e., a block of code) should start with an indentation, and the ending of the code should be the first line that is not indented. The common practice to execute an indentation is four white spaces or a single tab character, with areas being largely preferred over tabs.

As discussed earlier, the leading whitespaces at the start of a line determine the line’s indentation level. To group the statements for a particular code block, you will have to increase the indent level. Similarly, to close the grouping, you will have to reduce the indent level. 

Checkout: 42 Exciting Python Project Topic & Ideas

Causes of Indentation Error in Python

The ‘Indentation Error: Expected an indented block’ does not discriminate between users. Whether you are a novice at Python programming or an experienced software developer, this is bound to happen at some point in time. In Python, since all the code you type is arranged via correct whitespaces, if at any instance in the code, you have an incorrect indentation, the overall code with not run, and the interpreter will return an error function. To know exactly what to keep an eye out for, the following lists some of the common causes of an indentation error in Python:

1. The simultaneous use of tabs and space while coding. It can be argued that in theory, both tabs and spaces serve the same purpose, but let us consider this from the perspective of the interpreter. If white spaces and tabs are used inconsistently and interchangeably, it creates ambiguity. This will result in the interpreter getting confused between which alteration to use and eventually returning an indentation error in Python.

2. You have unintentionally placed an indentation in the wrong place or an absence of tabs or white spaces between code lines. Since Python adheres to strict guidelines to arrange written codes, an indentation in the wrong place will inevitably return an error. For example, the first line of Python should not be indented. 

3. Occasionally, while finishing an overdue, exceptionally long program, you might unknowingly miss out on indenting compound statement functions such as for, while and if. This will again lead to an indentation error. This is the most basic need for indentation when using Python and needs to be rigorously practised to master.

4. If you have forgotten to use indentation when working with user-defined functions or different classes, an error is likely to pop up. 

upGrad’s Exclusive Data Science Webinar for you –

How upGrad helps for your Data Science Career?

Explore our Popular Data Science Courses

How to solve an indentation error in Python?

1. Check for wrong white spaces or tabs. Unfortunately, there is no quick fix to an indentation error. Since the code is yours, the fact remains that you will have to assess each line to identify erroneous instances individually. However, since lines of code are arranged in blocks, the process is relatively simple. For example, if you have used the ‘if’ statement in a particular sequence, you can cross-check if you have remembered to indent the following line.

2. Be certain that the indentation for a specific block remains the same throughout the code, even if a new block is introduced in the middle. Check for inconsistencies in the indentation.

If the above manual solutions did not work for you, and you are having a hard time figuring out where you missed the indentation, then follow these steps:

3. Go to your code editor settings and enable the option that seeks to display tabs and whitespaces. With this feature enabled, you will see single small dots, where each dot represents a tab/white space. If you notice a drop is missing where it shouldn’t be, then that line probably has an indentation error.

4. Use the Python interpreter built-in Indent Guide. Arguably, this method is highly inefficient for several code lines. However, since it takes you through each line and shows you exactly where your error lies, it is the surest way to find and fix all errors. 

Also Read: Top 12 Fascinating Python Applications in Real World

Read our popular Data Science Articles

Benefits of Indentation

Readability and consistency are essential for any good code. Following the PEP 8 whitespace, ethics should thus be non-negotiable. It logically substantiates your code, thereby contributing to a more pleasant coding experience. Additionally, if you follow this stylistic guideline where readability is your de facto, people who are unknown to you, but are interested in your work, will understand your code with ease. 

Disadvantages of Indentation              

  • If the code is large and the indentation is corrupted, it can be tedious to fix indentation errors. This is usually when a code is copying from an online source, Word document or PDF file. 
  • Popular programming languages typically use braces for indentation. For programmers just beginning to use Python, adjusting to the idea of using whitespaces for indentation can be difficult. 

Top Data Science Skills to Learn in 2022

Summing Up

All that lies between you and a well-written code is an indentation, and all that lies between you, your well-written code and its seamless execution is an indentation error. Now, all humans make mistakes. All programmers are humans. Therefore, all programmers make mistakes. But an indentation error can easily be resolved. All you need to do is breathe and take your space. 

I hope you will learn a lot while working on these python projects. If you are curious about learning data science to be in front of fast-paced technological advancements, check out upGrad & IIIT-B’s Executive PG Programme in Data Science and upskill yourself for the future.

What errors can I get due to indentation in Python?

Python determines when code blocks begin and stop by looking at the space at the beginning of the line. You may encounter the following Indentation errors:
1. Unexpected indent — This line of code has more spaces at the beginning than the one before it, but the one before it does not begin a subblock. In a block, all lines of code must begin with the same string of whitespace.
2. Unindent does not correspond to any of the outer indentation levels — This line of code contains less spaces at the beginning than the previous one, but it also does not match any other block.
3. An indented block was expected — This line of code begins with the same number of spaces as the previous one, yet the previous line was supposed to begin a block (e.g., if/while/for statement, function definition).

How do you fix inconsistent tabs and spaces in indentation Spyder?

Tabs and spaces are two separate characters that appear on the screen as whitespace. The issue is that there is no consensus on how big a tab character should be, thus some editors display it as taking up 8 spaces, others as 4 spaces, and others as 2, and it’s also customizable.
When you code but one line is indented with a tab and the other with spaces, Python throws an error, despite the fact that it seems good in the editor (but it won’t look fine if you double the width of a tab; now the tab lines will be indented two levels).
To avoid this problem, go to your text editor’s options and enable the convert tabs to spaces feature, which replaces the tab character with n space characters, where n is the tab width your editor uses.

How do you show indents on Spyder?

Select your code and press Tab or Shift + Tab to indent or un-indent it. Other tools for altering your code can be found in the Edit section.

Want to share this article?

Prepare for a Career of the Future

If you are new to coding or an experienced coder, you might have come across indentation error in python. It looks silly but it can pause the entire process and take good amount of time to fix it. I can help you saving some of your precious time. So, lets dive little deeper into it and understand what is indentation and how to fix it

Python is a procedural language. An indentation in Python is used to segregate a singular code into identifiable groups of functionally similar statements. The indentation error can occur when the spaces or tabs are not placed properly. There will not be an issue if the interpreter does not find any issues with the spaces or tabs. If there is an error due to indentation, it will come in between the execution and can be a show stopper.

Python follows the PEP8 whitespace ethics while arranging its code and therefore it is suggested that there should be 4 whitespaces between every iteration and any alternative that doesn’t have this will return an error.

Below are some of the common causes of an indentation error in Python:

  • While coding you are using both the tab as well as space. While in theory both of them serve the same purpose, if used alternatively in a code, the interpreter gets confused between which alteration to use and thus returns an error.

  • While programming you have placed an indentation in the wrong place. Since python follows strict guidelines when it comes to arranging the code, if you placed any indentation in the wrong place, the indentation error is mostly inevitable.

  • Sometimes in the midst of finishing a long program, we tend to miss out on indenting the compound statements such as for, while and if and this in most cases will lead to an indentation error.

  • Last but not least, if you forget to use user defined classes, then an indentation error will most likely pop up.

Errors due to indentation in Python:

Python determines when code blocks begin and stop by looking at the space at the beginning of the line. You may encounter the following Indentation errors:
1. Unexpected indent — This line of code has more spaces at the beginning than the one before it, but the one before it does not begin a sub block. In a block, all lines of code must begin with the same string of whitespace.
2. Unindent does not correspond to any of the outer indentation levels — This line of code contains less spaces at the beginning than the previous one, but it also does not match any other block.
3. An indented block was expected — This line of code begins with the same number of spaces as the previous one, yet the previous line was supposed to begin a block (e.g., if/while/for statement, function definition).

Few tips to solve an indentation error in Python:

1. While there is no quick fix to this problem, one thing that you need to keep in mind while trying to find a solution for the indentation error is the fact that you have to go through each line individually and find out which one contains the error.

In Python, all the lines of code are arranged according to blocks, so it becomes easier for you to spot an error. For example, if you have used the if statement in any line, the next line must definitely have an indentation.

Take a look at the example below.

If you need guidance on how the correct form of indentation will look like, take a look at the example below.

2. Go to your code editor settings and enable the option that seeks to display tabs and whitespaces. With this feature enabled, you will see single small dots, where each dot represents a tab/white space. If you notice a drop is missing where it shouldn’t be, then that line probably has an indentation error.

For Pycharm, please go to file — settings — editor — code style — python

3. Use the Python interpreter built-in Indent Guide. It takes you through each line and shows you exactly where your error lies, it is the surest way to find and fix all errors.

Conclusion:

Getting errors are inevitable part of programming, so is debugging. One cannot ignore indentation error while working with python but above tips show that it can be easily resolved. Hope this information makes your life little easy and programming journey more exciting.

References:

https://www.edureka.co/blog/indentation-error-in-python/

Python is one of the leading and emerging programming platforms in the world of programming today. With its vast array of features and great flexibility, one can achieve a lot on this platform, given they know how to operate it. In this Indentation Error in Python Following pointers will be covered.

  • A Small Introduction to Indentation
  • The cause of Indentation Error in Python
  • A Solution to the Indentation Error
  • 2nd Solution
  • Conclusion

One of the most interesting queries that we get from coders of all expertise level and experience is how to fix the indentation error in python and in this article we will discuss more in detail about just that.

Let’s Begin!

A Small Introduction to Indentation

Before we dive down into the specifics of why an indentation error happens in the first place, let us first get acquainted with a basic idea of Python.

Python as a programming language was first introduced in the year 1991 and since then programmers around the world have adapted to it and created various applications both for the web and mobile. In Python, all the code that you type is arranged via correct whitespaces and therefore if at any instance you have a bad indentation, the overall code will not run and the interpreter will simply return an error function.

Python LogoA quick about the indentation error is that no matter if you are a pro or a newbie at programming, this is bound to happen to you at some point in time or the other.

Python follows the PEP8 whitespace ethics while arranging its code and therefore it is suggested that there should be 4 whitespaces between every iteration and any alternative that doesn’t have this will return an error.

Moving on with this article on Identation Error in Python

The cause of Indentation Error in Python

As mentioned in the introduction paragraph, one of the main reasons for the indentation error is the absence of tabs and or whitespaces between lines of code. Since python makes use of procedural language, if you miss out on adding tabs or spaces between your lines of code, then you will most likely experience this error. Although in some cases the entire program will run correctly, in others the error will come in the middle of the execution and therefore pause the entire process.

Mentioned below are some of the common causes of an indentation error in Python:

  • While coding you are using both the tab as well as space. While in theory both of them serve the same purpose, if used alternatively in a code, the interpreter gets confused between which alteration to use and thus returns an error.
  • While programming you have placed an indentation in the wrong place. Since python follows strict guidelines when it comes to arranging the code, if you placed any indentation in the wrong place, the indentation error is mostly inevitable.
  • Sometimes in the midst of finishing a long program, we tend to miss out on indenting the compound statements such as for, while and if and this in most cases will lead to an indentation error.
  • Last but not least, if you forget to use user defined classes, then an indentation error will most likely pop up.

Find out our Python Training in Top Cities/Countries

India USA Other Cities/Countries
Bangalore New York UK
Hyderabad Chicago London
Delhi Atlanta Canada
Chennai Houston Toronto
Mumbai Los Angeles Australia
Pune Boston UAE
Kolkata Miami Dubai
Ahmedabad San Francisco Philippines

A solution to the Indentation Error

Now that you know why this error is caused in the first place, let us explore some of the solutions to it.

#1 Solution

While there is no quick fix to this problem, one thing that you need to keep in mind while trying to find a solution for the indentation error is the fact that you have to go through each line individually and find out which one contains the error.

In Python, all the lines of code are arranged according to blocks, so it becomes easier for you to spot an error. For example, if you have used the if statement in any line, the next line must definitely have an indentation.

Take a look at the example below.

Example- Indentation error in python- Edureka

If you need guidance on how the correct form of indentation will look like, take a look at the example below.

Example - Identation error in Python- Edureka

#2 Solution

If the above-mentioned solution didn’t work for you, and you are having a hard time figuring out which line you have missed the indentation at, then follow these steps. Go to the setting of your code editor and enable the option which shows the tab and whitespaces. Once this feature in turned on, you will see small single dots in between your code, where each dot represents whitespace or a tab. If you see that a dot is missing somewhere that it needs to be, then that line probably has the indentation error.

To enable the option in order to view the tabs or whitespaces, take a look at the image below.

Example

Another option to get out of this problem is to use the built in Indent Guide in the Python interpreter.

Enabling this option will guide through each line of code and show you exactly where your error lies. Although this method is highly inefficient taking into consideration that your program contains several lines of code, this is the surest way to find and fix all existing errors.

Conclusion

Python is one of the most popular and adaptable programming languages out there. With its support for a wide variety of programming styles and languages, it is easily one of the most preferred choices for developers and coders worldwide. But even so, indentation error in Python, that everyone faces once in a while.

Using the solutions mentioned above you can easily fix your indentation error in Python and continue programming efficiently into the future. All the best. To learn more join our Python master course.

With this, we come to an end of this Indentation error in Python article. To get in-depth knowledge on Python along with its various applications, you can enroll now for live online Python training with 24/7 support and lifetime access.

If you’re trying to extend your business in this exciting field, check out our Artificial Intelligence Course. It is offered in collaboration with E&ICT Academy, National Institute of Technology, Warangal. This executive Masters’ Program equips students with information about the tools, techniques, and tools they require to advance their careers.

There are in fact multiples things you need to know about indentation in Python:

Python really cares about indention.

In a lot of other languages the indention is not necessary but improves readability. In Python indentation replaces the keyword begin / end or { } and is therefore necessary.

This is verified before the execution of the code, therefore even if the code with the indentation error is never reached, it won’t work.

There are different indention errors and you reading them helps a lot:

1. «IndentationError: expected an indented block»

They are two main reasons why you could have such an error:

— You have a «:» without an indented block behind.

Here are two examples:

Example 1, no indented block:

Input:

if 3 != 4:
    print("usual")
else:

Output:

  File "<stdin>", line 4

    ^
IndentationError: expected an indented block

The output states that you need to have an indented block on line 4, after the else: statement

Example 2, unindented block:

Input:

if 3 != 4:
print("usual")

Output

  File "<stdin>", line 2
    print("usual")
        ^
IndentationError: expected an indented block

The output states that you need to have an indented block line 2, after the if 3 != 4: statement

— You are using Python2.x and have a mix of tabs and spaces:

Input

def foo():
    if 1:
        print 1

Please note that before if, there is a tab, and before print there is 8 spaces.

Output:

  File "<stdin>", line 3
    print 1
      ^
IndentationError: expected an indented block

It’s quite hard to understand what is happening here, it seems that there is an indent block… But as I said, I’ve used tabs and spaces, and you should never do that.

  • You can get some info here.
  • Remove all tabs and replaces them by four spaces.
  • And configure your editor to do that automatically.

2. «IndentationError: unexpected indent»

It is important to indent blocks, but only blocks that should be indent.
So basically this error says:

— You have an indented block without a «:» before it.

Example:

Input:

a = 3
  a += 3

Output:

  File "<stdin>", line 2
    a += 3
    ^
IndentationError: unexpected indent

The output states that he wasn’t expecting an indent block line 2, then you should remove it.

3. «TabError: inconsistent use of tabs and spaces in indentation» (python3.x only)

  • You can get some info here.
  • But basically it’s, you are using tabs and spaces in your code.
  • You don’t want that.
  • Remove all tabs and replaces them by four spaces.
  • And configure your editor to do that automatically.

Eventually, to come back on your problem:

Just look at the line number of the error, and fix it using the previous information.

There are in fact multiples things you need to know about indentation in Python:

Python really cares about indention.

In a lot of other languages the indention is not necessary but improves readability. In Python indentation replaces the keyword begin / end or { } and is therefore necessary.

This is verified before the execution of the code, therefore even if the code with the indentation error is never reached, it won’t work.

There are different indention errors and you reading them helps a lot:

1. «IndentationError: expected an indented block»

They are two main reasons why you could have such an error:

— You have a «:» without an indented block behind.

Here are two examples:

Example 1, no indented block:

Input:

if 3 != 4:
    print("usual")
else:

Output:

  File "<stdin>", line 4

    ^
IndentationError: expected an indented block

The output states that you need to have an indented block on line 4, after the else: statement

Example 2, unindented block:

Input:

if 3 != 4:
print("usual")

Output

  File "<stdin>", line 2
    print("usual")
        ^
IndentationError: expected an indented block

The output states that you need to have an indented block line 2, after the if 3 != 4: statement

— You are using Python2.x and have a mix of tabs and spaces:

Input

def foo():
    if 1:
        print 1

Please note that before if, there is a tab, and before print there is 8 spaces.

Output:

  File "<stdin>", line 3
    print 1
      ^
IndentationError: expected an indented block

It’s quite hard to understand what is happening here, it seems that there is an indent block… But as I said, I’ve used tabs and spaces, and you should never do that.

  • You can get some info here.
  • Remove all tabs and replaces them by four spaces.
  • And configure your editor to do that automatically.

2. «IndentationError: unexpected indent»

It is important to indent blocks, but only blocks that should be indent.
So basically this error says:

— You have an indented block without a «:» before it.

Example:

Input:

a = 3
  a += 3

Output:

  File "<stdin>", line 2
    a += 3
    ^
IndentationError: unexpected indent

The output states that he wasn’t expecting an indent block line 2, then you should remove it.

3. «TabError: inconsistent use of tabs and spaces in indentation» (python3.x only)

  • You can get some info here.
  • But basically it’s, you are using tabs and spaces in your code.
  • You don’t want that.
  • Remove all tabs and replaces them by four spaces.
  • And configure your editor to do that automatically.

Eventually, to come back on your problem:

Just look at the line number of the error, and fix it using the previous information.

There are in fact multiples things you need to know about indentation in Python:

Python really cares about indention.

In a lot of other languages the indention is not necessary but improves readability. In Python indentation replaces the keyword begin / end or { } and is therefore necessary.

This is verified before the execution of the code, therefore even if the code with the indentation error is never reached, it won’t work.

There are different indention errors and you reading them helps a lot:

1. «IndentationError: expected an indented block»

They are two main reasons why you could have such an error:

— You have a «:» without an indented block behind.

Here are two examples:

Example 1, no indented block:

Input:

if 3 != 4:
    print("usual")
else:

Output:

  File "<stdin>", line 4

    ^
IndentationError: expected an indented block

The output states that you need to have an indented block on line 4, after the else: statement

Example 2, unindented block:

Input:

if 3 != 4:
print("usual")

Output

  File "<stdin>", line 2
    print("usual")
        ^
IndentationError: expected an indented block

The output states that you need to have an indented block line 2, after the if 3 != 4: statement

— You are using Python2.x and have a mix of tabs and spaces:

Input

def foo():
    if 1:
        print 1

Please note that before if, there is a tab, and before print there is 8 spaces.

Output:

  File "<stdin>", line 3
    print 1
      ^
IndentationError: expected an indented block

It’s quite hard to understand what is happening here, it seems that there is an indent block… But as I said, I’ve used tabs and spaces, and you should never do that.

  • You can get some info here.
  • Remove all tabs and replaces them by four spaces.
  • And configure your editor to do that automatically.

2. «IndentationError: unexpected indent»

It is important to indent blocks, but only blocks that should be indent.
So basically this error says:

— You have an indented block without a «:» before it.

Example:

Input:

a = 3
  a += 3

Output:

  File "<stdin>", line 2
    a += 3
    ^
IndentationError: unexpected indent

The output states that he wasn’t expecting an indent block line 2, then you should remove it.

3. «TabError: inconsistent use of tabs and spaces in indentation» (python3.x only)

  • You can get some info here.
  • But basically it’s, you are using tabs and spaces in your code.
  • You don’t want that.
  • Remove all tabs and replaces them by four spaces.
  • And configure your editor to do that automatically.

Eventually, to come back on your problem:

Just look at the line number of the error, and fix it using the previous information.

Indentation Error in Python

Introduction to Indentation Error in Python

Python is a language and is used for varied applications. Python is a language where the code is arranged through whitespaces. If there is an incorrect indentation, this will result in an error, and the python interpreter will just return an error function. It uses the PEP8 whitespace ethics. There should be 4 whitespaces used between any alternative or iteration. It happens mainly because of the absence of tabs and whitespaces between the lines of code. If there are any missing spaces between the code, you will face this error as Python is a procedural language.

Syntax:

There is no particular syntax for indentation. Instead of braces that are used in other languages, Python uses indentation. A block of code should start with indentation, and the ending of the code should be first-line which is not indented. The common practice is of adding four whitespaces which are usually preferred over tabs.

Example:

for i in range(1,24):
print(i)
if i == 8:
break

The spaces above will work properly as indentation is proper in the code, and it will run successfully.

How does Indentation Error work in Python?

Python is a procedural language. The indentation error can occur when the spaces or tabs are not placed properly. There will not be an issue if the interpreter does not find any issues with the spaces or tabs. If there is an error due to indentation, it will come in between the execution and can be a show stopper. You would be curious about what exactly causes these issues with indentation. Below are few reasons due to which this issue can happen.

  • The programmer is making use of both spaces and tabs in the code written. This creates ambiguity, and the interpreter is unable to determine which item we need to use in the first place as both are being used interchangeably.
  • The programmer missed upon indentation for compound statements like if, for, while, etc.
  • This is the most basic need when using Python. If the indentation technique is not practiced, then you will see this error every now and then.
  • It is very important that this indentation practice is used even when the programmer is working with user-defined functions or different classes.

The above are the usual cases where the user faces indentation errors while programming with Python. We will see a few examples of these errors ahead and also how to avoid them.

Examples of Indentation Error in Python

Let us see some examples where indentation error occurs and how we can resolve them.

Example #1

Code:

site = 'edu'
if site == 'edu':
print('Logging in to EduCBA!')
else:
     print('Please type the URL again.')
print('You are ready to go!')

This is a simple program where we are using the if-else block. Here we have declared a variable site that has the value. It has the value edu. We make use of if to check if the value in the site variable is edu, then it will display the desired message. If the variable is not the same, then the statement following else block will be displayed. Now syntactically, the above program is correct, and there is no error in the above code. But id you see the below screenshot, you will see an error has occurred.

Indentation Error in Python Example 1.1

You can clearly see there is an indentation error that has occurred. In order to overcome this error, we will have to use proper spacing for the print statement that follows the if block. The new code should be like the below in order to make the code work.

Code:

site = 'edu'
if site == 'edu':
   print('Logging in to EduCBA!')
else:
   print('Please type the URL again.')
print('You are ready to go!')

Indentation Error in Python Example 1.2

When the above code is run with proper whitespace, the desired output is received. The if block now runs successfully, and the output is received as expected.

Example #2

Code:

j = 1
while(j<= 5):
  print(j)
j = j + 1

The above code is a loop where the program should display numbers from 1 to 5. Here if you see the code, there is no alignment of spaces after the print(j) function. This leads to misplaced whitespaces. Here the code may or may not even throw an error. The interpreter just keeps running, or the output may be a blank screen. The output will be in either of the two ways.

Indentation Error in Python Example 2.1

Indentation Error in Python Example 2.2

It will either throw the above error or maybe just keep running. The correct way of writing this code is as below:

j = 1
while(j<= 5):
  print(j)
j = j + 1

The above code will run without throwing any errors and give the desired output. In python, we do not make use of braces, and hence indentation comes into the picture. Indentation plays an important role to keep the code systematic.

Example 2.3

As the indentation is correct in the above program, the output is as expected in the above screenshot.

How to Avoid Indentation Error in Python?

In order to not have an indentation error in Python, you must go through every line of your code separately. This will help you in understanding which line contains the error or does not have the expected whitespaces. Python arranges all lines of codes in the form of blocks. Hence just like there should be braces for the module, here should be spaces. You can just think that the braces are invisible, but they should be there in the form of spaces.

Another way of not facing this error is that you can simply go to your editor and enable the option to show the tabs and whitespaces. After this option is enabled, you can see dots on the editor where the dot act as space. If the dot is not being seen, then probably you have just generated an indentation error.

Conclusion

Python is a very user-friendly language. It mainly is similar to English and hence is being used widely. It makes use of whitespaces and tabs for keeping the code systematic. Like other languages, there is no need for any braces in Python. If these spaces are missed or misplaced, then an Indentation error occurs. It can be easily resolved by having proper spaces in the code.

Recommended Articles

This is a guide to Indentation Error in Python. Here we discuss the working of Indentation Error and how to avoid it in Python, along with different examples and its code implementation. You can also go through our other related articles to learn more –

  1. Control Statements in Python
  2. Python Private Variables
  3. Function Overloading in Python
  4. Python Pandas Join

In this post , we will see How to Fix Various Indentation Errors in Python.

Spacing is important in Python since the coding is dependent of the place or line where a code block starts or ends. Hence Indentation is crucial in Python coding.

P.S. – Once you read this post , go through our earlier post for extra tips –How To Fix – Indentation Problem in Python ? 


if( aicp_can_see_ads() ) {

}

Let us see the various types of Indentation Errors in Python –

1. IndentationError: unexpected indent –


Consider the example below –

>>>    print "hello world"
IndentationError: unexpected indent

The reason for this is the “EXTRA SPACE” before the command “print”

Fix –


if( aicp_can_see_ads() ) {

}

  • Check if  spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.
  • Remove Extra Spaces
    Better to use Spaces than Tabs.
  • For Sublime Text users –  Set Sublime Text to use tabs for indentation: View –> Indentation –> Convert Indentation to Tabs . Uncheck the Indent Using Spaces option as well in the same sub-menu above.
  • For  Notepad++ , Change Tab Settings to 4 spaces
    Go to Settings -> Preferences -> Tab Settings -> Replace by spaces

2. IndendationError: Unindent does not match any outer indentation level –


This happens when Python cannot decide whether a specific statement belongs to a specific Code-Block or Not (due to Indentation – might be copy-paste code).

For instance, in the following, is the final print supposed to be part of the if clause, or not?

Example Below –


if( aicp_can_see_ads() ) {

}

>>> if acc_name == "NYC":
...   print "New York Region !"
... print "Where do I belong ?"
IndendationError: unindent does not match any outer indentation level

Fix

  • Check if  spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.
  • Remove Extra Spaces
  • Better to use Spaces than Tabs.
  • For Sublime Text users –  Set Sublime Text to use tabs for indentation: View –> Indentation –> Convert Indentation to Tabs . Uncheck the Indent Using Spaces option as well in the same sub-menu above.
  • For  Notepad++ , Change Tab Settings to 4 spaces
    Go to Settings -> Preferences -> Tab Settings -> Replace by spaces

3. IndentationError: expected an indented block –


Normally occurs when a code block (if/while/for statement , function block etc.) , does not have spaces.  See example below –


if( aicp_can_see_ads() ) {

}

This line of code has the same number of spaces at the start as the one before, but the last line was expected to start a block (e.g. if/while/for statement, function definition).

>>> def foo():
... print "hello world"
IndentationError: expected an indented block

Fix


if( aicp_can_see_ads() ) {

}

  • Check if  spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.
  • Remove Extra Spaces
    Better to use Spaces than Tabs.
  • For Sublime Text users –  Set Sublime Text to use tabs for indentation: View –> Indentation –> Convert Indentation to Tabs . Uncheck the Indent Using Spaces option as well in the same sub-menu above.
  • For  Notepad++ , Change Tab Settings to 4 spaces
    Go to Settings -> Preferences -> Tab Settings -> Replace by spaces

Hope this helps .

Other Interesting Reads –

  • How To Fix – “Ssl: Certificate_Verify_Failed” Error in Python ?

  • How To Make Your Laptop or Desktop A Public Server (NGROK) ?

  • How To Setup Spark Scala SBT in Eclipse

  • How To Save & Reload a Python Machine Learning Model using Pickle ?

[the_ad id=”1420″]


if( aicp_can_see_ads() ) {

}

python indentation,python indentation error, unindent does not match any outer indentation level , expected an indented block , python expected an indented block, indentationerror, indented block python, indentation, python, pycharm, django, python fix indentation,python indentation fixer,python fix,python indentation rules,python fix indentation,indented block in python,indentationerror
python indentation ,python indentation checker ,python indentation error ,python indentationerror unexpected indent ,python indentation rules ,python indentation shortcut ,python indentationerror expected an indented block ,python indentation example ,python indentation error fix ,python indentation annoying ,python indentation automatic ,python indentation and spacing ,python indentation atom ,python indentation alternative ,python indentation arguments ,python indentation after while loop ,python indentation antlr ,python indentation best practices ,python indentation block ,python indentation brackets ,python indentation blank line ,python indentation broken ,python indentation button ,python indented block error ,python indent block of code ,python indentation codeforces ,python indentation convention ,python indentation contains tabs ,python indentation command line ,python indentation code ,python indentation does not match ,python indentation definition ,python indentation docs ,python indentation delete ,python indentation disable ,python indentation docstring ,python dictionary indentation ,python default indentation ,python indentation error fix online ,python indentation error check online ,python indentation error notepad++ ,python indentation error unindent ,python indentation formatter ,python indentation fix ,python indentation for loop ,python indentation for if ,python indentation function arguments ,python indentation function ,python indentation for ,python indentation format ,python indentation guide ,python indentation grammar ,python indentation geany ,vim indent python ,python get indentation level ,python get indentation ,python group indent ,python get index of string ,python indentation how many spaces ,python indentation hell ,python indentation helper ,python indentation haskell ,python indent html ,python indent hotkey ,python hanging indentation ,python heredoc indentation ,python indentation in visual studio code ,python indentation in notepad++ ,python indentation in hindi ,python indentation in vscode ,python indentation is not a multiple of four ,python indentation if statement ,python indentation in vim ,python indentation issues ,python indentation js ,python indent json ,python indent json command line ,indentation python jupyter ,python json indent=4 ,python json indent level ,python json indent tab ,python jsonpickle indent ,python kate indentation ,python keyboard indent indented python key ,python indentation long lines ,python indentation level ,python indentation line break ,python indentation length ,python indentation line ,python indent long if statement ,python indent left ,python indent list comprehension ,python indentation meaning ,python indentation meme ,python indentation multiple lines ,python indentation matters ,python indentation multiline string ,python mixed indentation ,python method indentation ,python markdown indentation ,python indentation notepad++ ,python indentation number of spaces ,python indentation not working ,python indentation new line ,python indentation nested ,python indentation number ,python indent no ,python notepad++ indentation error ,python indentation online ,python indentation of output ,python indentation of ,python-indent-offset ,python-indent-offset spacemacs ,python outer indentation level ,python object indentation ,python over-indented ,python indentation pep8 ,python indentation problem ,python indentation print ,python indentation pycharm ,python indentation purpose ,python indent plugin notepad++ ,python indent paragraph ,python print indentation error ,python triple quotes indentation ,qgis python indentation error ,indentation python c'est quoi ,python indentation reddit ,python indentation rules pdf ,python indentation return ,python indentation recommendation ,python indentation remove ,python indentation range ,python indentation right ,python indentation spaces ,python indentation space or tab ,python indentation solver ,python indentation sublime text 3 ,python indentation syntax ,python indentation size ,python indentation syntax error ,python indentation tool ,python indentation tab or space ,python indentation tab ,python indentation tutorial ,python indentation tab vs space ,python indentation try except ,python indentation tutorialspoint ,python indentation to spaces ,python indentation using ,python indent unindent ,python indent unexpected ,python uses indentation to indicate a block of code ,python uses indentation ,python uses indentation for blocks ,python unexpected indentation error ,python url indentation ,python indentation vscode ,python indentation validator ,python indentation vim ,python indentation vs braces ,python indentation visual studio ,python indentation variable scope ,python indentation vs spaces ,python indenting vs ,python indentation w3schools ,python indentation while loop ,python indentation windows linux ,python indentation width ,python indentation with 2 spaces ,python indentation wrong ,python indentation working ,python indent whole block ,python xml indentation ,python indentation in xcode ,xcode python indentation problems ,python yaml indentation ,python your indentation is outright incorrect ,python yaml indent list ,yasnippet python indentation ,youtube python indentation ,python indentation ,python indentation check ,python check indentation in notepad++ ,python indentation check online ,python indentation checker online ,python indent checker online ,python indent check online ,python indentation corrector ,python code indentation checker ,python indentation online checker ,python indentation check tool ,python indentation error sublime ,python indentation error after for loop ,python indentation error after if ,atom python indentation error ,python avoid indentation error ,python getting an indentation error ,python expected indented block error ,blender python indentation error ,check python indentation error ,python comment indentation error ,python class indentation error ,indentation error python codecademy ,python causing indentation error ,vs code python indentation error ,python command line indentation error ,python indentation error def ,python indentation error unindent does not match ,python docstring indentation error ,python error inconsistent indentation detected ,indentation error python deutsch ,python indentationerror expected an indented block for loop ,python indentation error example ,python indentation error else ,python indent expected error ,python elif indentation error ,python except indentation error ,indentation error python eclipse ,python indentation error for loop ,python indentation error for print ,python find indentation error ,python for indentation error ,indentation error in python for if ,geany python indentation error ,python keep getting indentation error ,python indentation error handling ,python how to fix indentation error ,how to check python indentation error ,python indentation error if ,indentation error in python ,indentation error in python 3 ,indentation error in python for loop ,indentation error in python print ,python idle indentation error ,indentation error in python vscode ,indentation error in python sublime text ,what is python indentation error ,how to handle indentation error in python ,python indentation error linux ,indentation error in python if loop ,indentation error meaning python ,maya python indentation error ,python multiline comment indentation error ,python indentation error nedir ,python nested if indentation error ,python indentation error online ,indentation error on python ,indentation error in python stack overflow ,raspberry pi python indentation error ,python indentation error remove ,python return indentation error ,python indentation error solve ,python shell indentation error ,python script indentation error ,visual studio python indentation error ,python if statement indentation error ,python terminal indentation error ,python try indentation error ,sublime text python indentation error ,python indentationerror unexpected unindent ,python indentationerror unexpected indent block ,python indentation error vim ,vscode python indentation error ,visual studio code python indentation error ,python while indentation error ,
python with indentation error ,indentation error in python while loop ,meaning of indentation error in python ,python indentationerror unexpected indent notepad++ ,python indentationerror unexpected indent comment ,vscode python indentationerror unexpected indent ,python 2.7 indentationerror unexpected indent ,python try indentationerror unexpected indent ,python ast indentationerror unexpected indent ,python exec indentationerror unexpected indent ,indentationerror unexpected indent python class ,python command line indentationerror unexpected indent ,indentationerror unexpected indent python visual studio code ,python def indentationerror unexpected indent ,python indentationerror unexpected indent error ,python if else indentationerror unexpected indent ,python parsing error indentationerror unexpected indent ,erro python indentationerror unexpected indent ,python for indentationerror unexpected indent ,indentationerror unexpected indent python for loop ,indentationerror unexpected indent python function ,python open file indentationerror unexpected indent ,python + indentationerror unexpected indent ,how to fix indentationerror unexpected indent in python ,indentationerror unexpected indent python ,indentation error in python unexpected indent ,indentationerror unexpected indent python 3 ,python indentationerror unexpected indent if ,indentationerror unexpected indent python jupyter notebook ,error unexpected indent python ,linux python indentationerror unexpected indent ,python for loop indentationerror unexpected indent ,python indentationerror unexpected indent print ,indentationerror unexpected indent pada python ,python unexpected indent for loop ,python shell indentationerror unexpected indent ,python sorry indentationerror unexpected indent ,python timeit indentationerror unexpected indent ,vim python indentationerror unexpected indent ,python while indentationerror unexpected indent ,what is indentationerror unexpected indent in python ,python 3 indentation rules ,indentation rules for python ,indentation rules in python ,indentation rules in python 3 ,python rules of indentation ,python idle indentation shortcut ,python auto indent shortcut ,vscode python indent shortcut ,python indent block shortcut ,indentation shortcut in python ,python shortcut for indentation ,shortcut key for indentation in python ,shortcut for indentation in python ,python indent shortcut ,indentation python shortcut ,python indentationerror expected an indented block if ,python indentationerror expected an indented block notepad++ ,python indentationerror expected an indented block try ,python interpreter indentationerror expected an indented block ,python elif indentationerror expected an indented block ,python return indentationerror expected an indented block ,python comment indentationerror expected an indented block ,error in python indentationerror expected an indented block ,how to fix expected an indented block in python ,python function indentationerror expected an indented block ,indentationerror expected an indented block in python ,python expected an indented block ,python print indentationerror expected an indented block ,python console indentationerror expected an indented block ,python class indentationerror expected an indented block ,python command line indentationerror expected an indented block ,python csv indentationerror expected an indented block ,python def indentationerror expected an indented block ,python indentationerror expected an indented block deutsch ,python error indentationerror expected an indented block ,erreur python indentationerror expected an indented block ,que significa en python indentationerror expected an indented block ,indentationerror expected an indented block python español ,erro python indentationerror expected an indented block ,how to fix indentationerror expected an indented block in python ,python fehler indentationerror expected an indented block ,python error expected an indented block ,how to remove indentationerror expected an indented block in python ,indentationerror expected an indented block in python for loop ,indentationerror expected an indented block in python script ,indentationerror expected an indented block meaning in python ,how to solve indentationerror expected an indented block ,python while loop indentationerror expected an indented block ,python indentationerror expected an indented block main ,python indentationerror expected an indented block print ,indentationerror expected an indented block print python 3 ,raspberry pi python indentationerror expected an indented block ,indentationerror expected an indented block python shell ,python sorry indentationerror expected an indented block ,python script indentationerror expected an indented block ,python if statement indentationerror expected an indented block ,python indentation how to ,python indentation tool ,python indentation to spaces ,python indentation to ,python how to fix indentation error ,python how to check indentation ,python how to fix indentation ,python how to create indentation ,python indentation annoying ,python indentation automatic ,python indentation atom ,python indentation and spacing ,python indentation alternative ,python indentation arguments ,python indentation after while loop ,python indentation antlr ,python indentation best practice ,python indentation block ,python indentation brackets ,python indentation blank line ,python indentation broken ,python indentation button ,,python indented block error ,python indent block of code ,python indentation checker ,python indentation check ,python indentation codeforces ,python indentation convention ,python indentation contains tabs ,python indentation command line ,python indentation correction ,python indentation contains mixed spaces and tabs ,python indentation does not match ,python indentation definition ,python indentation docs ,python indentation delete ,python indentation disable ,python indentation docstring ,python indentation error def ,indentation python docx ,python indentation error ,python indentation error fix ,python indentation error check online ,python indentation example ,python indentation error unindent ,python indentation explained ,python indentation editor online ,python indentation error notepad++ ,python indentation fixer ,python indentation formatter ,python indentation fix ,python indentation for loop ,python indentation function arguments ,python indentation function ,python indentation for if else ,python indentation for ,python indentation guide ,python indentation grammar ,python indentation geany ,vim indent python ,how to give indentation in python ,python indentation hell ,python indentation helper ,python indentation haskell ,python indent html ,python indent hotkey ,python indentation in hindi ,python indentation error handling ,indentation python help ,python indentation is not a multiple of four ,python indentation in vim ,python indentation if statement ,python indentation if else ,python indentation in notepad++ ,python indentation in visual studio code ,python indentation issues ,python indentation in sublime ,python indentation js ,python indented text to json ,python indent json ,python indent json command line ,indentation python jupyter ,python indent to left ,python indentation level ,python indentation long lines ,python indentation line break ,python indentation length ,python indentation line ,python indent long if statement ,python indent list comprehension ,python indentation how many spaces ,python indentation multiple lines ,python indentation meaning ,python indentation meme ,python indentation matters ,,python indentation multiline string ,how to make indentation in python ,python indentation notepad++ ,python indentation number of spaces ,python indentation not working ,python indentation new line ,python indentation nested ,python indentation number ,python indent no ,python indentation online ,python indentation of ,python indent output ,python-indent-offset ,python-indent-offset spacemacs ,python indentation 2 or 4 spaces ,python indentation tab or space ,python indentation problem ,python indentation pep8 ,python indentation print ,python indentation pycharm ,python indentation purpose ,python indent plugin notepad++ ,python indent paragraph ,indentation python programming ,python indentation rules ,python indentation rules pdf ,python indentation reddit ,python indentation return ,python indentation recommendation ,python indentation remove ,python indentation range ,python indentation right ,python indentation shortcut ,python indentation space or tab ,python indentation sublime text 3 ,python indentation size ,python indentation syntax ,python indentation syntax error ,python indentation spaces vs tabs ,python indentation tutorial ,python indentation tab vs space ,python indentation tab ,python indentation try except ,python indentation tutorialspoint ,python indentation using ,python indent unindent ,python indent unexpected ,python indentationerror unexpected unindent ,python indentation vim ,python indentation vscode ,python indentation validation ,python indentation validation online ,python indentation vs braces ,python indentation visual studio ,python indentation variable scope ,python indentation vs spaces ,python indentation w3schools ,python indentation while loop ,python indentation windows linux ,python indentation width ,python indentation with 2 spaces ,python indentation wrong ,python indentation working ,python indent whole block ,python indentation in xcode ,python formatter tool ,python fix indentation tool ,python indentation check tool ,indentation tool for python ,python indentation ,python indentation tool online ,python indent online ,python indent spaces or tab ,python indentation 4 spaces ,python indentation 2 spaces ,python indentation four spaces ,python tabs to spaces convert ,python tabs and spaces error ,python mixed indentation spaces found ,python indentation in spaces ,python tabs to spaces online ,python indentation space tab ,python convert tabs to spaces vim ,python tabs vs spaces ,python indent with spaces ,python write indented json to file ,python add indentation to string ,python uses indentation to indicate a block of code ,how to fix indentation error in python using notepad++ ,how to fix indentation error in python online ,python correct indentation errors ,how to fix an indentation error in python ,how to fix indentation error in python ,how to handle indentation error in python ,how to correct indentation error in python ,how to fix unexpected indent error in python ,python check indentation online ,python check indentation in notepad++ ,how to check python indentation error ,python check for indentation ,python check file indentation ,how to check indentation in python ,how to check indentation error in python ,python fix indentation online ,python fix indentation notepad++ ,python fix indentation vscode ,python fix indentation sublime ,python how to fix unexpected indent ,python spyder fix indentation ,python fix all indentation ,how to fix indented block in python ,python fix indentation command line ,how to fix indentation in sublime for python ,how to fix indentation in python ,how to fix python indentation in notepad++ ,how to fix indentation in python spyder ,how to fix indentation in python pycharm ,how to correct indentation in python jupyter notebook ,python fix indentation linux ,python fix mixed indentation ,how to fix indentation problem in python ,python fix indentation script ,how to fix the indentation in python ,python fix indentation vim ,python create indented block ,how to create indentation in python ,vim python automatic indentation ,python editor automatic indentation ,spyder python automatic indentation ,python disable automatic indentation ,python automatic indentation ,


if( aicp_can_see_ads() ) {


if( aicp_can_see_ads() ) {

}

}

Понравилась статья? Поделить с друзьями:
  • Incrementing error counter on sa attempt 2 of 5 retransmit phase 1
  • Incorrect syntax near sql ошибка
  • Incorrect skeleton type for anim 552 at creation как исправить
  • Incorrect path to ini file как исправить
  • Incorrect media paths media in config file expect some media to be missing как исправить