Python unexpected indent что за ошибка

от admin

Rectify an Unexpected Indent Error in Python

Python is a programming language that relies a lot on spacing. Proper spacing and indentation are essential in Python for the program to work without errors. Spacing or indentation in Python indicates a block of code.

Please enable JavaScript

In this article, you’ll learn how to rectify the unexpected indent error in Python.

Rectify the IndentationError: unexpected indent Error in Python

An unexpected indent occurs when we add an unnecessary space or tab in a line of the code block. The message IndentationError: unexpected indent is shown when we run the code if this type of error is contained within your program.

The following code below shows an example of when an unexpected indent error occurs.

In the example code above, we define a function ex1() , which contains two print statements. However, the second print statement has an unnecessary space or tab before it.

This code produces an unexpected indent error in line 3 as it encounters the additional space before the print(«It’s me») statement.

The following code rectifies the error contained in the previous program.

Python is a programming language that strictly enforces indentation. Indentation also increases the readability of the code.

Indentation can be done in Python using either spaces or the tab button; choosing which one depends entirely on the user. The Python code needs to be indented in some cases where one part of the code needs to be written in a block.

  • The if-else conditional statement
  • A for or a while loop
  • A simple function statement
  • A try. except statement

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

Python IndentationError: unexpected indent Solution

IndentationErrors serve two purposes: they help make your code more readable and ensure the Python interpreter correctly understands your code. If you add in an additional space or tab where one is not needed, you’ll encounter an “IndentationError: unexpected indent” error.

In this guide, we discuss what this error means and why it is raised. We’ll walk through an example of this error so you can figure out how you can fix it in your program.

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: unexpected indent

An indent is a specific number of spaces or tabs denoting that a line of code is part of a particular code block. Consider the following program:

We have defined a single function: hello_world() . This function contains a print statement. To indicate to Python this line of code is part of our function, we have indented it.

You can indent code using spaces or tabs, depending on your preference. You should only indent code if that code should be part of another code block. This includes when you write code in:

Python code must be indented consistently if it appears in a special statement. Python enforces indentation strictly.

Some programming languages like JavaScript do not enforce indentation strictly because they use curly braces to denote blocks of code. Python does not have this feature, so the language depends heavily on indentation.

The cause of the “IndentationError: unexpected indent” error is indenting your code too far, or using too many tabs and spaces to indent a line of code.

The other indentation errors you may encounter are:

An Example Scenario

We’re going to build a program that loops through a list of purchases that a user has made and prints out all of those that are greater than $25.00 to the console.

To start, let’s define a list of purchases:

Next, we define a function to loop through our list of purchases and print the ones worth over $25 to the console:

The show_high_purchases() function accepts one argument: the list of purchases through which the function will search. The function iterates through this list and uses an if statement to check if each purchase is worth more than $25.00.

If a purchase is greater than $25.00, the statement Purchase: is printed to the console. Then, the price of that purchase is printed to the console. Otherwise, nothing happens.

Before we run our code, call our function and pass our list of purchases as a parameter:

Let’s run our code and see what happens:

Our code does not run successfully.

The Solution

As with any Python error, we should read the full error message to see what is going on. The problem appears to be on line 7, which is where we print the value of a purchase.

We have incidentally indented the second print() statement. This causes an error because our second print() statement is not part of another block of code. It is still part of our if statement.

To solve this error, we need to make sure that we consistently indent all our print() statements:

Both print() statements should use the same level of indentation because they are part of the same if statement. We’ve made this revision above.

Let’s try to run our code:

Our code successfully prints out all the purchases worth more than $25.00 to the console.

Conclusion

“IndentationError: unexpected indent” is raised when you indent a line of code too many times. To solve this error, make sure all of your code uses consistent indentation and that there are no unnecessary indents.

Now you’re ready to fix this error like a Python expert!

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

How to fix indentation Error in Python

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.

What should I do with "Unexpected indent" in Python?

How do I rectify the error "unexpected indent" in Python?

Peter Mortensen's user avatar

18 Answers 18

Python uses spacing at the start of the line to determine when code blocks start and end. Errors you can get are:

Unexpected indent. This line of code has more spaces at the start than the one before, but the one before is not the start of a subblock (e.g., the if, while, and for statements). All lines of code in a block must start with exactly the same string of whitespace. For instance:

This one is especially common when running Python interactively: make sure you don’t put any extra spaces before your commands. (Very annoying when copy-and-pasting example code!)

Unindent does not match any outer indentation level. This line of code has fewer spaces at the start than the one before, but equally it does not match any other block it could be part of. Python cannot decide where it goes. For instance, in the following, is the final print supposed to be part of the if clause, or not?

Expected an indented block. 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 statements, or a function definition).

If you want a function that doesn’t do anything, use the "no-op" command pass:

Mixing tabs and spaces is allowed (at least on my version of Python), but Python assumes tabs are 8 characters long, which may not match your editor. Don’t mix tabs and spaces. Most editors allow automatic replacement of one with the other. If you’re in a team, or working on an open-source project, see which they prefer.

The best way to avoid these issues is to always use a consistent number of spaces when you indent a subblock, and ideally use a good IDE that solves the problem for you. This will also make your code more readable.

Похожие статьи