与python中的“意外缩进”怎么办?

问题:与python中的“意外缩进”怎么办?

如何纠正python中的“意外缩进”错误?

How do I rectify the error “unexpected indent” in python?


回答 0

Python在行的开头使用空格来确定代码块的开始和结束时间。您可以获得的错误是:

意外缩进。这行代码的开头比以前的空格多,但前面的不是子块的开头(例如if / while / for语句)。块中的所有代码行必须以完全相同的空格字符串开头。例如:

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

当以交互方式运行python时,这一点尤其常见:请确保不要在命令前放置任何多余的空格。(在复制粘贴示例代码时非常烦人!)

>>>   print "hello"
IndentationError: unexpected indent

Unindent与任何外部缩进级别都不匹配。这行代码的开头空格比以前的空格少,但是同样,它与它可能包含的任何其他块也不匹配。Python无法决定其去向。例如,在下面,最终的打印是否应该包含在if子句中?

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

预期缩进的块。这行代码的开头与前面的空格数量相同,但是最后一行应开始一个块(例如,if / while / for语句,函数定义)。

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

如果您想要一个不执行任何操作的函数,请使用“ no-op”命令传递

>>> def foo():
...     pass

允许混合使用制表符和空格(至少在我的Python版本中),但是Python假定制表符的长度为8个字符,可能与您的编辑器不匹配。只需对标签说“不”即可。大多数编辑器允许将它们自动替换为空格。

避免这些问题的最佳方法是在缩进子块时始终使用一致数量的空格,并且理想情况下使用可以为您解决问题的良好IDE。这也将使您的代码更具可读性。

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. if/while/for statement). 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 statement, 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. Just say “no” to tabs. Most editors allow them to be automatically replaced by spaces.

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.


回答 1

在Python中,间距非常重要,这给出了代码块的结构。当您弄乱代码结构时会发生此错误,例如:

def test_function() :
   if 5 > 3 :
   print "hello"

您的文件中可能还会包含选项卡和空格。

我建议您使用python语法感知编辑器,例如PyScripterNetbeans

In Python, the spacing is very important, this gives the structure of your code blocks. This error happens when you mess up your code structure, for example like this :

def test_function() :
   if 5 > 3 :
   print "hello"

You may also have a mix of tabs and spaces in your file.

I suggest you use a python syntax aware editor like PyScripter, or Netbeans


回答 2

使用-tt选项运行您的代码,以查明您是否不一致地使用了制表符和空格

Run your code with the -tt option to find out if you are using tabs and spaces inconsistently


回答 3

在使用的任何编辑器中打开可见的空白,并打开带空格的替换选项卡。

虽然可以将选项卡与Python混合使用,但通常将选项卡和空格混合会导致您遇到错误。建议使用4个空格替换制表符,这是编写Python代码的推荐方法。

Turn on visible whitespace in whatever editor you are using and turn on replace tabs with spaces.

While you can use tabs with Python mixing tabs and space usually leads to the error you are experiencing. Replacing tabs with 4 spaces is the recommended approach for writing Python code.


回答 4

通过使用正确的缩进。Python具有空格意识,因此您需要按照其块的缩进指南进行操作,否则会出现缩进错误。

By using correct indentation. Python is whitespace aware, so you need to follow its indentation guidlines for blocks or you’ll get indentation errors.


回答 5

如果您使用Sublime编写Python并出现缩进错误,

查看->缩进->将缩进转换为空格

我描述的问题是由Sublime文本编辑器引起的。同样的问题也可能由其他编辑器引起。从本质上讲,这个问题与Python希望以空格来处理缩进有关,而各种编辑器都以制表符来编写缩进。

If you’re writing Python using Sublime and getting indentation errors,

view -> indentation -> convert indentation to spaces

The issue I’m describing is caused by the Sublime text editor. The same issue could be caused by other editors as well. Essentially, the issue has to do with Python wanting to treat indentations in terms of spaces versus various editors coding the indentations in terms of tabs.


回答 6

确保在编辑器中使用选项“插入空格而不是制表符”。然后,您可以选择所需的制表符宽度,例如4。您可以在gedit中的edit-> preferences-> editor下找到这些选项。

底线:使用空间而不是选项卡

Make sure you use the option “insert spaces instead of tabs” in your editor. Then you can choose you want a tab width of, for example 4. You can find those options in gedit under edit–>preferences–>editor.

bottom line: USE SPACES not tabs


回答 7

将某些内容粘贴到Python解释器(终端/控制台)中时,也会发生此错误。

请注意,解释器会将空行解释为表达式的末尾,因此如果您粘贴类似

def my_function():
    x = 3

    y = 7

解释器将在解释之前将空行解释y = 7为表达式的末尾,也就是说,您已经完成了对函数的定义,而下一行- y = 7由于它是新表达式,因此缩进不正确。

This error can also occur when pasting something into the Python interpreter (terminal/console).

Note that the interpreter interprets an empty line as the end of an expression, so if you paste in something like

def my_function():
    x = 3

    y = 7

the interpreter will interpret the empty line before y = 7 as the end of the expression, i.e. that you’re done defining your function, and the next line – y = 7 will have incorrect indentation because it is a new expression.


回答 8

似乎没有提到的一个问题是,由于与缩进无关的代码问题,此错误可能会出现。

例如,使用以下脚本:

def add_one(x):
    try:
        return x + 1
add_one(5)

IndentationError: unexpected unindent当问题当然是缺少except:语句时,这将返回。

我的观点:检查上面报告意外(un)缩进的代码!

One issue which doesn’t seem to have been mentioned is that this error can crop up due to a problem with the code that has nothing to do with indentation.

For example, take the following script:

def add_one(x):
    try:
        return x + 1
add_one(5)

This returns an IndentationError: unexpected unindent when the problem is of course a missing except: statement.

My point: check the code above where the unexpected (un)indent is reported!


回答 9

如果缩进没问题,请查看您的编辑器是否具有“查看空白”选项。启用它应该可以找到空格和制表符混合的位置。

If the indentation looks ok then have a look to see if your editor has a “View Whitespace” option. Enabling this should allow to find where spaces and tabs are mixed.


回答 10

有一个对我总是有用的技巧:

如果您意外缩进,并且发现所有代码均已缩进,请尝试使用其他编辑器将其打开,然后您会看到未缩进的代码行。

当我使用vim,gedit或类似的编辑器时,这件事发生在我身上。

尝试仅将1个编辑器用于您的代码。

There is a trick that always worked for me:

If you got and unexpected indent and you see that all the code is perfectly indented, try opening it with another editor and you will see what line of code is not indented.

It happened to me when used vim, gedit or editors like that.

Try to use only 1 editor for your code.


回答 11

只需复制您的脚本,然后在整个代码“””下放入“”即可…

在变量中指定此行。

a = """ your python script """
print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four char space as per pep 8 style guide..

现在在Sublime Editor中使用ctrl + b执行此代码,现在它将在控制台中打印缩进的代码。而已

Simply copy your script and put under “”” your entire code “”” …

specify this line in a variable.. like,

a = """ your python script """
print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four char space as per pep 8 style guide..

now execute this code, in Sublime Editor using ctrl+b, now it will print indented code in console. that’s it


回答 12

您需要做的就是从以下代码的开头删除空格或制表符空格

from django.contrib import admin

# Register your models here.
from .models import Myapp
admin.site.register(Myapp)

All You need to do is remove spaces or tab spaces from the start of following codes

from django.contrib import admin

# Register your models here.
from .models import Myapp
admin.site.register(Myapp)

回答 13

运行以下命令以解决该问题:

autopep8 -i <filename>.py

这将更新您的代码并解决所有缩进错误:)

希望这能解决

Run the following command to get it solved :

autopep8 -i <filename>.py

This will update your code and solve all indentation Errors :)

Hope this will solve


回答 14

Notepad ++提供了正确的制表符空间,但最终在Sublime文本编辑器中发现了缩进问题。

使用Sublime文本编辑器并逐行进行

Notepad++ was giving the tab space correct but the indentation problem was finally found in Sublime text editor.

Use Sublime text editor and go line by line


回答 15

与许多其他编程语言不同,Python中的缩进很重要,这并不是为了代码可读性。如果连续命令之间的代码中有空格或制表符,则python将给出此错误,因为Python对此很敏感。当我们将代码复制并粘贴到任何Python时,我们很可能会遇到此错误。 确保使用文本编辑器(如Notepad ++)标识并删除这些空格,或者从出现错误的代码行中手动删除空格。

Step1 :Gives error 
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print(L[2: ])

Step2: L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]print(L[2: ])

Step3: No error after space was removed
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print(L[2: ])
OUTPUT: [[7, 8, 9, 10]]

谢谢!

Indentation in Python is important and this is just not for code readability, unlike many other programming languages. If there is any white space or tab in your code between consecutive commands, python will give this error as Python is sensitive to this. We are likely to get this error when we do copy and paste of code to any Python. Make sure to identify and remove these spaces using a text editor like Notepad++ or manually remove the whitespace from the line of code where you are getting an error.

Step1 :Gives error 
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print(L[2: ])

Step2: L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]print(L[2: ])

Step3: No error after space was removed
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print(L[2: ])
OUTPUT: [[7, 8, 9, 10]]

Thanks!