IndentationError:unindent与任何外部缩进级别都不匹配

问题:IndentationError:unindent与任何外部缩进级别都不匹配

当我编译下面的Python代码时,我得到

IndentationError:unindent与任何外部缩进级别都不匹配


import sys

def Factorial(n): # Return factorial
    result = 1
    for i in range (1,n):
        result = result * i
    print "factorial is ",result
    return result

为什么?

When I compile the Python code below, I get

IndentationError: unindent does not match any outer indentation level


import sys

def Factorial(n): # Return factorial
    result = 1
    for i in range (1,n):
        result = result * i
    print "factorial is ",result
    return result

Why?


回答 0

其他海报可能是正确的…选项卡中可能混有空格。尝试执行搜索和替换操作,以将所有标签替换为几个空格。

尝试这个:

import sys

def Factorial(n): # return factorial
    result = 1
    for i in range (1,n):
        result = result * i
    print "factorial is ",result
    return result

print Factorial(10)

Other posters are probably correct…there might be spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.

Try this:

import sys

def Factorial(n): # return factorial
    result = 1
    for i in range (1,n):
        result = result * i
    print "factorial is ",result
    return result

print Factorial(10)

回答 1

重要说明空格是首选方法 -请参阅PEP008 缩进制表符或空格?。(感谢@Siha。)

对于Sublime Text用户:

设置Sublime Text为使用制表符进行缩进: View-> Indentation->Convert Indentation to Tabs

Indent Using Spaces还要取消选中上面相同子菜单中的选项。这将立即解决此问题。

IMPORTANT: Spaces are the preferred method – see PEP008 Indentation and Tabs or Spaces?. (Thanks to @Siha for this.)

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. This will immediately resolve this issue.


回答 2

要轻松检查制表符/空格的问题,您可以执行以下操作:

python -m tabnanny yourfile.py

或者您当然可以正确设置编辑器:-)

To easily check for problems with tabs/spaces you can actually do this:

python -m tabnanny yourfile.py

or you can just set up your editor correctly of course :-)


回答 3

您确定不在缩进空格中混用制表符和空格吗?(这将导致该错误。)

请注意,建议您不要在Python代码中使用制表符。请参阅样式指南。您应该配置Notepad ++以便为选项卡插入空格。

Are you sure you are not mixing tabs and spaces in your indentation white space? (That will cause that error.)

Note, it is recommended that you don’t use tabs in Python code. See the style guide. You should configure Notepad++ to insert spaces for tabs.


回答 4

每当遇到此错误时,都是因为我以某种方式混淆了编辑器中的制表符和空格。

Whenever I’ve encountered this error, it’s because I’ve somehow mixed up tabs and spaces in my editor.


回答 5

如果使用Python的IDLE编辑器,则可以按照类似的错误消息之一进行操作:

1)全选,例如Ctrl+A

2)转到格式->取消制表区域

3)仔细检查您的缩进是否仍然正确,保存并重新运行您的程序。

我正在使用Python 2.5.4

If you use Python’s IDLE editor you can do as it suggests in one of similar error messages:

1) select all, e.g. Ctrl + A

2) Go to Format -> Untabify Region

3) Double check your indenting is still correct, save and rerun your program.

I’m using Python 2.5.4


回答 6

如果您使用的是Vim,请按Escape键,然后输入

gg = G

这会自动缩进所有内容,并清除您抛出的所有空格。

If you are using Vim, hit escape and then type

gg=G

This auto indents everything and will clear up any spaces you have thrown in.


回答 7

这行:result = result * i应该缩进(这是for循环的主体)。

或者-您混合使用空格和制表符

The line: result = result * i should be indented (it is the body of the for-loop).

Or – you have mixed space and tab characters


回答 8

原子上

Packages > Whitespace > Convert Spaces to Tabs

然后再次检查您的文件缩进:

python -m tabnanny yourFile.py

要么

>python
>>> help("yourFile.py")

On Atom

go to

Packages > Whitespace > Convert Spaces to Tabs

Then check again your file indentation:

python -m tabnanny yourFile.py

or

>python
>>> help("yourFile.py")

回答 9

看起来是一个缩进问题。你不必匹配在Python大括号,但你必须匹配缩进层次。

防止空格/制表符问题的最佳方法是在文本编辑器中显示不可见的字符。这将为您提供预防和/或解决与缩进相关的错误的快速方法。

同样,注入复制粘贴的代码是此类问题的常见来源。

Looks to be an indentation problem. You don’t have to match curly brackets in Python but you do have to match indentation levels.

The best way to prevent space/tab problems is to display invisible characters within your text editor. This will give you a quick way to prevent and/or resolve indentation-related errors.

Also, injecting copy-pasted code is a common source for this type of problem.


回答 10

如果使用notepad ++,请使用扩展搜索模式“替换”以找到\ t并用四个空格替换。

If you use notepad++, do a “replace” with extended search mode to find \t and replace with four spaces.


回答 11

对于Atom用户,Packages ->whitspace -> remove trailing whitespaces 这对我有用

for Atom Users, Packages ->whitspace -> remove trailing whitespaces this worked for me


回答 12

只是一个补充。我在Notepad ++中的两个缩进都有类似的问题。

  1. 无exceptions的缩进
  2. 外压痕等级

    转到—->搜索选项卡—->点击替换 —->选中单选按钮扩展到下面—>现在用四个空格替换\ t

    转到—->搜索选项卡—->点击替换 —->按下单选按钮扩展到下面—>现在将\ n替换为空

Just a addition. I had a similar problem with the both indentations in Notepad++.

  1. Unexcepted indentation
  2. Outer Indentation Level

    Go to —-> Search tab —-> tap on replace —-> hit the radio button Extended below —> Now replace \t with four spaces

    Go to —-> Search tab —-> tap on replace —-> hit the radio button Extended below —> Now replace \n with nothing


回答 13

我使用的是Jupyter笔记本,尝试了几乎所有上述解决方案(以适应我的情况)为无效。然后,我一行一行地删除了每一行的所有空格,并用tab代替了。那解决了问题。

I was using Jupyter notebook and tried almost all of the above solutions (adapting to my scenario) to no use. I then went line by line, deleted all spaces for each line and replaced with tab. That solved the issue.


回答 14

对于Spyder用户,请 转至源>修复缩进以立即解决问题

For Spyder users goto Source > Fix Indentation to fix the issue immediately


回答 15

可能是因为其上方的函数缩进方式不同。即

class a:
    def blah:
      print("Hello world")
    def blah1:
      print("Hello world")

It could be because the function above it is not indented the same way. i.e.

class a:
    def blah:
      print("Hello world")
    def blah1:
      print("Hello world")

回答 16

昨天我遇到了同样的问题,这是缩进错误,正在使用崇高的文本编辑器。花了我几个小时的时间来修复它,最后我最终将代码复制到VI文本编辑器中,并且运行良好。ps python对空格太敏感,请确保不要混合使用空格和制表符。

I had the same issue yesterday, it was indentation error, was using sublime text editor. took my hours trying to fix it and at the end I ended up copying the code into VI text editor and it just worked fine. ps python is too whitespace sensitive, make sure not to mix space and tab.


回答 17

因为我意识到没有特定的答案spyder,所以我将添加一个答案:基本上,仔细查看您的if声明并确保全部ifelifelse具有相同的间距,即它们在开始时位于同一行,如下所示:

def your_choice(answer):
    if answer>5:
        print("You're overaged")
    elif answer<=5 and answer>1: 
            print("Welcome to the toddler's club!")
    else:
            print("No worries mate!")

Since I realize there’s no answer specific to spyder,I’ll add one: Basically, carefully look at your if statement and make sure all if, elif and else have the same spacing that is they’re in the same line at the start like so:

def your_choice(answer):
    if answer>5:
        print("You're overaged")
    elif answer<=5 and answer>1: 
            print("Welcome to the toddler's club!")
    else:
            print("No worries mate!")

回答 18

我定义了一个函数,但除了函数注释外,它没有任何内容

def foo(bar):
    # Some awesome temporary comment.
    # But there is actually nothing in the function!
    # D'Oh!

大喊:

  File "foobar.py", line 69

                                ^
IndentationError: expected an indented block

(请注意,^标记指向的行为空)

多种解决方案:

1:仅将功能注释掉

2:添加功能注释

def foo(bar):
    '' Some awesome comment. This comment could be just one space.''

3:添加不执行任何操作的行

def foo(bar):
    0

在任何情况下,请务必使其明显的 ,为什么它是一个空的功能-为自己,或您的同事将使用代码

I had a function defined, but it did not had any content apart from its function comments…

def foo(bar):
    # Some awesome temporary comment.
    # But there is actually nothing in the function!
    # D'Oh!

It yelled :

  File "foobar.py", line 69

                                ^
IndentationError: expected an indented block

(note that the line the ^ mark points to is empty)

Multiple solutions:

1: Just comment out the function

2: Add function comment

def foo(bar):
    '' Some awesome comment. This comment could be just one space.''

3: Add line that does nothing

def foo(bar):
    0

In any case, make sure to make it obvious why it is an empty function – for yourself, or for your peers that will use your code


回答 19

首先,只是提醒您有一个逻辑错误,您最好保持result = 1,否则即使在循环运行后,您的输出也将为result = 0。

其次,您可以这样编写:

import sys

def Factorial(n): # Return factorial
  result = 0
  for i in range (1,n):
     result = result * i

  print "factorial is ",result
  return result

留下一行将告诉python shell FOR语句已经结束。如果您有使用python shell的经验,那么您可以理解为什么我们必须行。

Firstly, just to remind you there is a logical error you better keep result=1 or else your output will be result=0 even after the loop runs.

Secondly you can write it like this:

import sys

def Factorial(n): # Return factorial
  result = 0
  for i in range (1,n):
     result = result * i

  print "factorial is ",result
  return result

Leaving a line will tell the python shell that the FOR statements have ended. If you have experience using the python shell then you can understand why we have to leave a line.


回答 20

对于它的价值,我的文档字符串缩进太多,这也引发了相同的错误

class junk: 
     """docstring is indented too much""" 
    def fun(): return   

IndentationError: unindent does not match any outer indentation level

For what its worth, my docstring was indented too much and this also throws the same error

class junk: 
     """docstring is indented too much""" 
    def fun(): return   

IndentationError: unindent does not match any outer indentation level


回答 21

这是因为制表符和空格混在一起。您可以删除所有空格,然后将其替换为制表符。

或者,尝试编写以下代码:

#!/usr/bin/python -tt

在代码的开头。此行解决了制表符和空格之间的所有差异。

This is because there is a mix-up of both tabs and spaces. You can either remove all the spaces and replace them with tabs.

Or, Try writing this:

#!/usr/bin/python -tt

at the beginning of the code. This line resolves any differences between tabs and spaces.


回答 22

就我而言,问题是在Eclipse上配置pydev

in my case, the problem was the configuration of pydev on Eclipse


回答 23

如果使用Komodo编辑器,则可以按照以下类似错误消息之一的建议进行操作:

1)全选,例如Ctrl + A

2)转到代码->取消制表区域

3)仔细检查您的缩进是否仍然正确,保存并重新运行您的程序。

我正在使用Python 3.4.2

If you use Komodo editor you can do as it suggests in one of similar error messages:

1) select all, e.g. Ctrl + A

2) Go to Code -> Untabify Region

3) Double check your indenting is still correct, save and rerun your program.

I’m using Python 3.4.2


回答 24

如果您将Sublime文本用于python开发,则可以使用Anaconda软件包来避免该错误。安装Anaconda后,

  1. 崇高地打开文件
  2. 右键单击开放空间
  3. 选择水蟒
  4. 点击自动格式化
  5. 完成或按CTRL + ALT + R。

If you are using Sublime text for python development,you can avoid the error by using the package Anaconda.After installing Anaconda,

  1. open your file in sublime
  2. right click on the open spaces
  3. choose anaconda
  4. click on autoformat
  5. DONE Or Press CTRL+ALT+R.

回答 25

在具有python插件的intellij中,按Ctrl + Shift + Alt重新格式化文档可解决缩进/制表符/空格问题

In intellij with python plugin, Ctrl + Shift + Alt to reformat the document fixed the indent/tab/spaces problem


回答 26

对于SPYDER用户:我将spyder 3.3.2与python 3.7.1结合使用,并解决了此问题,将缩进设置为使用选项卡,并通过以下步骤单击:

  • 工具。
  • 偏好。
  • 编辑。
  • 高级设置。
  • 缩进字符->制表符。

然后,使用Tab键重置“ unidented”行。

由于某种原因,如果没有此设置,有时会出现幽灵 IndentationError。

For SPYDER users: I’m using spyder 3.3.2 with python 3.7.1 and I solved this, setting indentation to use tabs, with the following steps, click on:

  • Tools.
  • Preferences.
  • Editor.
  • Advanced settings.
  • Indentation characters -> Tabs.

Then I reset the “unidented” line using tab key.

For some reason, without this setting, I got the ghost IndentationError sometimes.


回答 27

例如:

1. def convert_distance(miles):
2.   km = miles * 1.6
3.   return km

在这段代码中,我也遇到了同样的情况。只需删除第2行和第3行的先前缩进空格,然后使用tab或空格即可。切勿同时使用两者。在用python编写代码时,给出适当的缩进。对于Spyder,请转至源>修复缩进。VC代码和崇高文本或任何其他编辑器也是如此。修复缩进。

For example:

1. def convert_distance(miles):
2.   km = miles * 1.6
3.   return km

In this code same situation occurred for me. Just delete the previous indent spaces of line 2 and 3, and then either use tab or space. Never use both. Give proper indentation while writing code in python. For Spyder goto Source > Fix Indentation. Same goes to VC Code and sublime text or any other editor. Fix the indentation.


回答 28

发生这种情况的主要原因是编辑器。尝试将选项卡更改为spaces(4)。最佳的Python友好IDE或编辑器是pycharm,sublime,vim(对于Linux)。
即使我也遇到过同样的问题,后来我发现还有一个编码问题。我建议您也更改您的编辑器。

This happens mainly because of editor .Try changing tabs to spaces(4).the best python friendly IDE or Editors are pycharm ,sublime ,vim for linux.
even i too had encountered the same issue , later i found that there is a encoding issue .i suggest u too change ur editor.