Ошибка неожиданный отступ в питоне

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:

>>> def a():
...   print "foo"
...     print "bar"
IndentationError: unexpected indent

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!)

>>>   print "hello"
IndentationError: unexpected indent

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?

>>> if user == "Joey":
...     print "Super secret powers enabled!"
...   print "Revealing super secrets"
IndendationError: unindent does not match any outer indentation level

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).

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

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

>>> def foo():
...     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.

Вопросик, я только начал изучать питон, учусь по книжке, там говорят про отступы, но почему выдает ошибку IndentationError: unexpected indent? там не перемешаны пробелы и табы, я пробовал и 4 пробела везде проставить и табы, ошибка одна( код вообще рандомный, просто для проверки сделал)

df = (200, 300)
	print('обычный форма:')
	print(df)

df = (300, 400)
	print('nмодернизация:')
	print(df)


  • Вопрос задан

    22 мар.

  • 5601 просмотр

Так и пишет, неожиданный отступ.

Если код так и выглядит

df = (200, 300)
  print('обычный форма:')
  print(df)

df = (300, 400)
  print('nмодернизация:')
  print(df)

То ошибка вполне логична, перед print() зачем-то стоят отступы, которых быть не должно

Пригласить эксперта


  • Показать ещё
    Загружается…

14 июн. 2023, в 00:43

5000 руб./за проект

13 июн. 2023, в 23:37

1000 руб./в час

13 июн. 2023, в 23:22

15000 руб./за проект

Минуточку внимания

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:

def hello_world():
	print("Hello, world!")

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:

  • An “if…else” statement
  • A “try…except” statement
  • A “for” loop
  • A “function” statement

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:

  • Unindent does not match any other indentation level
  • Expected an indented block

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:

 purchases = [25.50, 29.90, 2.40, 57.60, 24.90, 1.55]

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

def show_high_purchases(purchases):
	   for p in purchases:
		        if p > 25.00:
			            print("Purchase: ")
				                print(p)

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:

show_high_purchases(purchases)

Let’s run our code and see what happens:

  File "main.py", line 7
	print(p)
	^
IndentationError: unexpected indent

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.

	if p > 25.00:
			print("Purchase: ")
				    print(p)

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:

	if p > 25.00:
			print("Purchase: ")
			print(p)

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:

Purchase:
25.5
Purchase:
29.9
Purchase:
57.6

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!

Table of Contents
Hide
  1. What are the reasons for IndentationError: unexpected indent?
    1. Python and PEP 8 Guidelines 
  2. Solving IndentationError: expected an indented block
  3. Example 1 – Indenting inside a function
  4. Example 2 – Indentation inside for, while loops and if statement
  5. Conclusion

Python language emphasizes indentation rather than using curly braces like other programming languages. So indentation matters in Python, as it gives the structure of your code blocks, and if you do not follow it while coding, you will get an indentationerror: unexpected indent.

What are the reasons for IndentationError: unexpected indent?

IndentationError: unexpected indent mainly occurs if you use inconsistent indentation while coding. There are set of guidelines you need to follow while programming in Python. Let’s look at few basic guidelines w.r.t indentation.

Python and PEP 8 Guidelines 

  1. Generally, in Python, you follow the four spaces rule according to PEP 8 standards
  2. Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs.
  3. Do not mix tabs and spaces. Python disallows the mixing of indentation.
  4. Avoid trailing whitespaces anywhere because it’s usually invisible and it causes confusion.

Solving IndentationError: expected an indented block

Now that we know what indentation is and the guidelines to be followed, Let’s look at few indentation error examples and solutions.

Example 1 – Indenting inside a function

Lines inside a function should be indented one level more than the “def functionname”. 

# Bad indentation inside a function

def getMessage():
message= "Hello World"
print(message)
  
getMessage()

# Output
  File "c:ProjectsTryoutslistindexerror.py", line 2
    message= "Hello World"
    ^
IndentationError: expected an indented block

Correct way of indentation while creating a function.

# Proper indentation inside a function

def getMessage():
    message= "Hello World"
    print(message)
  
getMessage()

# Output
Hello World

Example 2 – Indentation inside for, while loops and if statement

Lines inside a for, if, and while statements should be indented more than the line, it begins the statement so that Python will know when you are inside the loop and when you exit the loop.

Suppose you look at the below example inside the if statement; the lines are not indented properly. The print statement is at the same level as the if statement, and hence the IndentationError.

# Bad indentation inside if statement
def getMessage():
    foo = 7
    if foo > 5:
    print ("Hello world")
  
getMessage()

# Output
  File "c:ProjectsTryoutslistindexerror.py", line 4
    print ("Hello world")
    ^
IndentationError: expected an indented block

To fix the issues inside the loops and statements, make sure you add four whitespaces and then write the lines of code. Also do not mix the white space and tabs these will always lead to an error.

# Proper indentation inside if statement
def getMessage():
    foo = 7
    if foo > 5:
        print ("Hello world")
  
getMessage()

# Output
Hello world

Conclusion

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.

Avatar Of Srinivas Ramakrishna

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:

def hello_world():
	print("Hello, world!")

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:

  • An “if…else” statement
  • A “try…except” statement
  • A “for” loop
  • A “function” statement

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:

  • Unindent does not match any other indentation level
  • Expected an indented block

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:

 purchases = [25.50, 29.90, 2.40, 57.60, 24.90, 1.55]

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

def show_high_purchases(purchases):
	   for p in purchases:
		        if p > 25.00:
			            print("Purchase: ")
				                print(p)

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:

show_high_purchases(purchases)

Let’s run our code and see what happens:

  File "main.py", line 7
	print(p)
	^
IndentationError: unexpected indent

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.

	if p > 25.00:
			print("Purchase: ")
				    print(p)

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:

	if p > 25.00:
			print("Purchase: ")
			print(p)

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:

Purchase:
25.5
Purchase:
29.9
Purchase:
57.6

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!

Table of Contents
Hide
  1. What are the reasons for IndentationError: unexpected indent?
    1. Python and PEP 8 Guidelines 
  2. Solving IndentationError: expected an indented block
  3. Example 1 – Indenting inside a function
  4. Example 2 – Indentation inside for, while loops and if statement
  5. Conclusion

Python language emphasizes indentation rather than using curly braces like other programming languages. So indentation matters in Python, as it gives the structure of your code blocks, and if you do not follow it while coding, you will get an indentationerror: unexpected indent.

What are the reasons for IndentationError: unexpected indent?

IndentationError: unexpected indent mainly occurs if you use inconsistent indentation while coding. There are set of guidelines you need to follow while programming in Python. Let’s look at few basic guidelines w.r.t indentation.

Python and PEP 8 Guidelines 

  1. Generally, in Python, you follow the four spaces rule according to PEP 8 standards
  2. Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs.
  3. Do not mix tabs and spaces. Python disallows the mixing of indentation.
  4. Avoid trailing whitespaces anywhere because it’s usually invisible and it causes confusion.

Solving IndentationError: expected an indented block

Now that we know what indentation is and the guidelines to be followed, Let’s look at few indentation error examples and solutions.

Example 1 – Indenting inside a function

Lines inside a function should be indented one level more than the “def functionname”. 

# Bad indentation inside a function

def getMessage():
message= "Hello World"
print(message)
  
getMessage()

# Output
  File "c:ProjectsTryoutslistindexerror.py", line 2
    message= "Hello World"
    ^
IndentationError: expected an indented block

Correct way of indentation while creating a function.

# Proper indentation inside a function

def getMessage():
    message= "Hello World"
    print(message)
  
getMessage()

# Output
Hello World

Example 2 – Indentation inside for, while loops and if statement

Lines inside a for, if, and while statements should be indented more than the line, it begins the statement so that Python will know when you are inside the loop and when you exit the loop.

Suppose you look at the below example inside the if statement; the lines are not indented properly. The print statement is at the same level as the if statement, and hence the IndentationError.

# Bad indentation inside if statement
def getMessage():
    foo = 7
    if foo > 5:
    print ("Hello world")
  
getMessage()

# Output
  File "c:ProjectsTryoutslistindexerror.py", line 4
    print ("Hello world")
    ^
IndentationError: expected an indented block

To fix the issues inside the loops and statements, make sure you add four whitespaces and then write the lines of code. Also do not mix the white space and tabs these will always lead to an error.

# Proper indentation inside if statement
def getMessage():
    foo = 7
    if foo > 5:
        print ("Hello world")
  
getMessage()

# Output
Hello world

Conclusion

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.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

1 ответ

Если бы вы перевели текст ошибки, вы бы поняли, что у вас проблема с отступами.
Обратите внимание на отступ перед import.

Напоминаю, что в python блоки кода разграничиваются отступами.

Если питон счёл, что у вас вложенность кода обозначается четырьмя
пробелами, а именно эта строка отбита одним табом, то будет такая
ошибка.

На основе этого ответа.

В данном случае отступ вообще следует удалить.

ответ дан 26 фев 2016 в 21:13

VenZell's user avatar

VenZellVenZell

19.8k5 золотых знаков43 серебряных знака61 бронзовый знак

1

  • Окей , у меня такая же проблема но в коде .( Я учусь и решил написать простой калькулятор) Но удаляю абсолютно все отступы которые присутствуют в коде и все равно также ошибка .

    26 фев 2019 в 13:38

Понравилась статья? Поделить с друзьями:
  • Ошибка неоднозначная ссылка на столбец postgresql
  • Ошибка необработанное исключение в приложении
  • Ошибка необрабатываемое исключение в приложении при нажатии кнопки продолжить
  • Ошибка необрабатываемое исключение в приложении как исправить
  • Ошибка необрабатываемое исключение в приложении miflash