我应该如何处理“意外缩进”? 在Python中?

发布于 2024-07-25 03:59:20 字数 30 浏览 8 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

梦里的微风 2024-08-01 03:59:21

如果您使用 Sublime Text 编写 Python 并遇到缩进错误,

菜单查看缩进将缩进转换为空格

我描述的问题是由 Sublime Text 编辑器引起的。 其他编辑器也可能会引起同样的问题。 本质上,这个问题与 Python 希望按照空格来处理缩进以及各种编辑器按照制表符编码缩进有关。

If you're writing Python using Sublime Text and are getting indentation errors,

Menu ViewIndentationConvert 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.

扮仙女 2024-08-01 03:59:21

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

例如,采用以下脚本:

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

当问题当然是缺少 except: 语句时,这会返回 IndentationError:意外的 unindent

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

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!

假面具 2024-08-01 03:59:21

确保您在编辑器中使用“插入空格而不是制表符”选项。 然后你可以选择你想要的制表符宽度,例如 4。你可以在 gedit 菜单编辑首选项编辑器

底线:使用空格,而不是制表符

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 menu EditpreferencesEditor.

Bottom line: use spaces, not tabs

白况 2024-08-01 03:59:21

将某些内容粘贴到 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.

掩耳倾听 2024-08-01 03:59:21

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

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.

眼泪淡了忧伤 2024-08-01 03:59:21

这取决于上下文。 尚未涵盖的另一种情况如下。 假设您有一个文件,其中包含一个带有特定方法的类

class Scraper:
    def __init__(self):
        pass

    def scrape_html(self, html: str):
        pass

,并且在该文件的底部您有类似

if __name__ == "__main__":
    # some
    # commands
    # doing
    # stuff

使整个文件看起来像这样的内容

class Scraper:
    def __init__(self):
        pass

    def scrape_html(self, html: str):
        pass

if __name__ == "__main__":
    # some
    # commands
    # doing
    # stuff

如果在 scrape_html() 中打开,例如,一个 if/else语句

class Scraper:
    def __init__(self):
        pass

    def scrape_html(self, html: str):
        if condition:
            pass
        else:

if __name__ == "__main__":
    parser = argparse.ArgumentParser()

您需要将 pass 或任何您想要的内容添加到 else 语句中,否则您将得到

预期的缩进块

“在此处输入图像描述"

不需要取消缩进

“在此处输入图像描述"

预期表达

在此处输入图像描述

并在第一行中

输入

意外缩进

在此处输入图像描述

添加 pass 将解决所有这四个问题。

It depends in the context. Another scenario which wasn't yet covered is the following. Let's say you have one file with a class with a specific method in it

class Scraper:
    def __init__(self):
        pass

    def scrape_html(self, html: str):
        pass

and in the bottom of the file you have something like

if __name__ == "__main__":
    # some
    # commands
    # doing
    # stuff

making it the whole file look like this

class Scraper:
    def __init__(self):
        pass

    def scrape_html(self, html: str):
        pass

if __name__ == "__main__":
    # some
    # commands
    # doing
    # stuff

If in scrape_html() you open up, for example, an if/else statement

class Scraper:
    def __init__(self):
        pass

    def scrape_html(self, html: str):
        if condition:
            pass
        else:

if __name__ == "__main__":
    parser = argparse.ArgumentParser()

You'll need to add pass or whatever you want to to that else statement or else you'll get

Expected indented block

enter image description here

Unindent not expected

enter image description here

Expected expression

enter image description here

and in the first row

Unexpected indentation

enter image description here

Adding that pass would fix all of these four problems.

始终不够爱げ你 2024-08-01 03:59:21

有一个技巧一直对我有用:

如果您遇到意外的缩进,并且发现所有代码都完美缩进,请尝试使用另一个编辑器打开它,您将看到哪一行代码没有缩进。

当我使用 Vim 时,就发生了这种情况,gedit,或类似的编辑器。

尝试仅使用一个代码编辑器。

There is a trick that always worked for me:

If you got an 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 I used Vim, gedit, or editors like that.

Try to use only one editor for your code.

桜花祭 2024-08-01 03:59:21

只需复制您的脚本,并将其放在“””您的整个代码“””下...

在变量中指定这一行...例如,

a = """ your Python script """

print a.replace("Here please press the tab button. It will insert some space", " here simply press the space bar four times.")
#
# Here we are replacing tab space by four character
# space as per the PEP 8 style guide...
#
# Now execute this code. In the Sublime Text
# editor use Ctrl + B. Now it will print
# indented code in the console. That's it.

Simply copy your script, and put it under """ your entire code """ ...

Specify this line in a variable... like,

a = """ your Python script """

print a.replace("Here please press the tab button. It will insert some space", " here simply press the space bar four times.")
#
# Here we are replacing tab space by four character
# space as per the PEP 8 style guide...
#
# Now execute this code. In the Sublime Text
# editor use Ctrl + B. Now it will print
# indented code in the console. That's it.
流星番茄 2024-08-01 03:59:21

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

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 the following code:

from django.contrib import admin

# Register your models here.
from .models import Myapp
admin.site.register(Myapp)
调妓 2024-08-01 03:59:21

Notepad++ 给出了正确的制表符空间,但最终发现了缩进问题Sublime Text 编辑器。

使用 Sublime Text 编辑器并逐行进行。

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

Use the Sublime Text editor and go line by line.

疯狂的代价 2024-08-01 03:59:21

与许多其他编程语言不同,Python 中的缩进很重要,但这并不是为了代码可读性。

如果代码中连续命令之间存在任何空格或制表符,Python 会给出此错误,因为 Python 对此很敏感。 当我们将代码复制并粘贴到任何 Python 时,我们很可能会遇到此错误。

确保使用诸如 之类的文本编辑器识别并删除这些空格Notepad++ 或手动删除出现错误的代码行中的空格。

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

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

# Step 3: 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.

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

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

# Step 3: 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]]
兔姬 2024-08-01 03:59:21

这取决于上下文,但缩进错误通常是由于使用制表符而不是空格引起的。

您可以采取以下一些步骤来纠正此问题:

  1. 复制导致错误的制表符或空格

  2. 在 IDE 中进行查找和替换(通常为 Ctrl + H)。

  3. 将复制的制表符或空格粘贴到“查找”搜索栏中,然后将它们全部替换为四个空格(假设您的 IDE 使用四个空格作为“良好”缩进)

如果您复制并粘贴代码,也会经常发生此错误从外部源导入到您的 IDE 中,因为其他地方的格式可能与您的 IDE 对“良好”缩进的定义不匹配。

It depends on the context, but an indentation error is often caused by using tabs instead of spaces.

Here are some steps you can take to correct this:

  1. Copy the tabs or spaces that are causing the error

  2. Do a find and replace in your IDE (usually Ctrl + H).

  3. Paste the copied tabs or spaces into the "Find" search bar, and then replace them all with four spaces (assuming that your IDE uses four spaces as a "good" indentation)

This error also happens a lot if you are copying and pasting code from external sources into your IDE, because the formatting elsewhere may not match your IDE's definition for what counts as a "good" indentation.

£噩梦荏苒 2024-08-01 03:59:21

检查你的括号
我收到此错误是因为我忘记关闭一个括号

print("some text"
pandas.do_something()

Check your brackets
I've got this error because I forgot to close one bracket

print("some text"
pandas.do_something()
╰沐子 2024-08-01 03:59:20

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

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

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

这种情况在交互式运行 Python 时尤其常见:确保命令前没有添加任何额外的空格。 (复制粘贴示例代码时非常烦人!)

>>>   print "hello"
IndentationError: unexpected indent

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

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

需要一个缩进块。这行代码的开头空格数与前一行相同,但最后一行预计会开始一个块(例如,ifwhilefor 语句或函数定义)。

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

如果你想要一个不做任何事情的函数,请使用“no-op”命令pass

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

獨角戲 2024-08-01 03:59:20

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

梦醒时光 2024-08-01 03:59:20

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

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

只是偏爱你 2024-08-01 03:59:20

在您使用的任何编辑器中打开可见空白,并打开用空格替换制表符

虽然您可以在 Python 中使用制表符,但混合使用制表符和空格通常会导致您遇到错误。 用四个空格替换制表符是编写 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 four spaces is the recommended approach for writing Python code.

谁人与我共长歌 2024-08-01 03:59:20

通过使用正确的缩进。 Python 能够识别空格,因此您需要遵循其块缩进指南,否则会出现缩进错误。

By using correct indentation. Python is white space aware, so you need to follow its indentation guidelines for blocks or you'll get indentation errors.

鹤舞 2024-08-01 03:59:20

运行以下命令来解决它:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文