我得到一个IndentationError。如何解决? [英] I'm getting an IndentationError. How do I fix it?

查看:443
本文介绍了我得到一个IndentationError。如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python脚本:

  if True:
if False:
print foo')
print('bar')

但是,当我尝试运行我的脚本,Python引发了一个 IndentationError

 文件script.py ,第4行
print('bar')
^
IndentationError:unindent不匹配任何外部缩进级别

我一直在玩我的程序,我也可以产生另外三个错误:




  • IndentationError:unexpected indent

  • IndentationError:expected a indented block

  • TabError:缩进中使用制表符和空格不一致



这些错误是什么意思?我究竟做错了什么?如何修复我的代码?

解决方案

为什么缩进有用?



在Python中,缩进用于定义



特殊情况



注意Python 不会 总是提高 TabError 标签和空格进入您的程序。如果程序缩进是明确的,Python将允许标签和空格混合。例如:

 >>>如果True:
...如果True:#tab
... pass#tab,then 4 spaces
...
>>>

有时候,Python只会在标签和空格的混合上扼制,并且错误地引发了一个 TabError 的indentationError 异常会更合适。另一个例子:

 >>>如果True:
... pass#tab
... pass#4 spaces
文件< stdin>,第3行
pass#4空格
^
IndentationError:unindent不匹配任何外部缩进级别

正如你所看到的,运行你的代码这样可以产生神秘的错误。即使视觉上的程序看起来很好,Python变得困惑,试图解析用于缩进和错误的标签和空格。



这些是一个很好的例子,展示了为什么不要混合标签和空格,并利用 -t -tt 解释器标志使用Python 2。



修正



如果您的程序很短,最简单和最简单的修复是简单地重新缩进程序。确保每个语句每个缩进级别缩进四个空格(请参阅 如何缩进我的代码 )。



但是,如果您已经有一个大型程序,您已经混合了选项卡和空格,那么可以使用自动化工具将所有缩进转换为空格。



许多编辑器,如 PyCharm SublimeText 具有自动将制表符转换为空格的选项。还有几种在线工具,例如标签到空格浏览器,让您快速重新缩进代码。还有用P​​ython编写的工具。 autopep8 例如可以自动重新缩进您的代码和其他缩进错误。



即使是最好的工具,有时也无法修复所有的缩进错误,您必须手动修复它们。这就是为什么始终要正确缩进代码很重要。



我仍然很难使用Python的缩进语法。我该怎么办?



如果你还在努力,不要气馁需要时间才能使用
Python的空格语法规则。这里有一些帮助的提示:




  • 获取一个编辑器,当您有缩进错误时会告诉您。一些商品如上所述, PyCharm SublimeText Jupyter Notebook

  • 当您缩进代码时,请大声地向自己排除多少次按空格键(或标签键)。例如,如果您需要按四个空格缩进一行,您可以大声说出一个两个三个四个,同时每次都按住空格键。这听起来很愚蠢,但是它有助于训练你的大脑,想想你的代码有多深。

  • 如果你有一个编辑器,看看它是否有一个选项来自动将标签转换成

  • 查看他人的代码。浏览 github Stackoverflow ,并查看Python代码的例子。

  • 只需编写代码即可。这是获得更好的最好的方法。你编写的Python代码越多,你会得到的越好。



使用的资源




I have a Python script:

if True:
    if False:
        print('foo')
   print('bar')

However, when I attempt to run my script, Python raises an IndentationError:

  File "script.py", line 4
    print('bar')
               ^
IndentationError: unindent does not match any outer indentation level

I kept playing around with my program, and I was also able to produce three other errors:

  • "IndentationError: unexpected indent"
  • "IndentationError: expected an indented block"
  • "TabError: inconsistent use of tabs and spaces in indentation"

What do these errors mean? What am I doing wrong? How can I fix my code?

解决方案

Why does indentation matter?

In Python, indentation is used to delimit blocks of code. This is different from many other languages that use curly braces {} to delimit blocks such as Java, Javascript, and C. Because of this, Python users must pay close attention to when and how they indent their code because whitespace matters.

When Python encounters a problem with the indentation of your program, it either raises an exception called IndentationError or TabError.

A little history

The historical reasons for why Python uses indentation vs the arguably more commonly accepted curly braces {} is outlined in an article of the history of Python by Guido van Rossum - the creator of Python:

Python’s use of indentation comes directly from ABC, but this idea didn’t originate with ABC--it had already been promoted by Donald Knuth and was a well-known concept of programming style. (The occam programming language also used it.) However, ABC’s authors did invent the use of the colon that separates the lead-in clause from the indented block. After early user testing without the colon, it was discovered that the meaning of the indentation was unclear to beginners being taught the first steps of programming. The addition of the colon clarified it significantly: the colon somehow draws attention to what follows and ties the phrases before and after it together in just the right way.

How do I indent my code?

The basic rule for indenting Python code (considering that you treat the entire program as a "basic block") is: The first statement in a basic block, and each subsequent statement after it must be indented by the same amount.

So technically the following Python program is correct:

def perm(l):
        # Compute the list of all permutations of l
    if len(l) <= 1:
                  return [l]
    r = []
    for i in range(len(l)):
             s = l[:i] + l[i+1:]
             p = perm(s)
             for x in p:
              r.append(l[i:i+1] + x)
    return r

However, as you can probably tell from above, randomly indenting your code makes is extremely hard to read and follow the flow of the program. It's better to be consistent and follow a style.

PEP8 - The Python style guide - recommends that four spaces per indentation level should be used:

Use 4 spaces per indentation level.

That is, each statement that is starting a new block and each subsequent statement in the new block, should be indented four spaces from the current indentation level. Here is the above program indented according to the PEP8 style guide:

def perm(l):
    # Compute the list of all permutations of l
    if len(l) <= 1:
        return [l]
    r = []
    for i in range(len(l)):
        s = l[:i] + l[i+1:]
        p = perm(s)
        for x in p:
            r.append(l[i:i+1] + x)
    return r

Can I still use tabs?

Python realizes that some people still prefer tabs over spaces and that legacy code may use tabs rather than spaces, so it allows the use of tabs as indentation. PEP8 touches on this topic:

Spaces are the preferred indentation method.

Tabs should be used solely to remain consistent with code that is already indented with tabs.

Note however the one big caveat is not to use both tabs and spaces for indentation. Doing so can cause all kinds of strange hard to debug indentation errors. The Python 3 compiler explicitly rejects any program containing an ambiguous mixture of tabs and spaces, usually by raising a TabError. However, by default, mixing tabs and spaces is still allowed in Python 2, but it is highly recommended not to use this "feature". Use the -t and -tt command line flags to force Python 2 to raise a warning or (preferably) an error respectively. PEP8 also discusses this topic:

Python 3 disallows mixing the use of tabs and spaces for indentation.

Python 2 code indented with a mixture of tabs and spaces should be converted to using spaces exclusively.

When invoking the Python 2 command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!

What does "IndentationError: unexpected indent" mean?

Problem

This error occurs when a statement is unnecessarily indented or its indentation does not match the indentation of former statements in the same block. For example, the first statement in the program below is unnecessarily indented:

>>>  print('Hello') # this is indented 
  File "<stdin>", line 1
    print('Hello') # this is indented 
    ^
IndentationError: unexpected indent

In this example, the can_drive = True line in the if block does not match the indentation of any former statement:

>>> age = 10
>>> can_drive = None
>>> 
>>> if age >= 18:
...     print('You can drive')
...      can_drive = True # incorrectly indented
  File "<stdin>", line 3
    can_drive = True # incorrectly indented
    ^
IndentationError: unexpected indent

Fix

The fix for this error is to first make sure the problematic line even needs to be indented. For example, the above example using print can be fixed simply be unindenting the line:

>>> print('Hello') # simply unindent the line
Hello

However, if you are sure the line does need to be indented, the indentation needs to match that of a former statement in the same block. In the second example above using if, we can fix the error by making sure the line with can_drive = True is indented at the same level as the former statements in the if body:

>>> age = 10
>>> can_drive = None
>>> 
>>> if age >= 18:
...     print('You can drive')
...     can_drive = True # indent this line at the same level.
... 

What does "IndentationError: expected an indented block" mean?

Problem

This error occurs when Python sees the 'header' for a compound statement, such as if <condition>: or while <condition>: but the compound statement's body or block is never defined. For example in the code below we began an if statement, but we never define a body for the statement:

>>> if True:
... 
  File "<stdin>", line 2

    ^
IndentationError: expected an indented block

In this second example, we began writing a for loop, but we forget to indent the for loop body. So Python still expects an indented block for the for loop body:

>>> names = ['sarah', 'lucy', 'michael']
>>> for name in names:
... print(name)
  File "<stdin>", line 2
    print(name)
        ^
IndentationError: expected an indented block

Comments don't count as bodies:

>>> if True:
...     # TODO
...
  File "<stdin>", line 3

    ^
IndentationError: expected an indented block

Fix

The fix for this error is to simply include a body for the compound statement.

As shown above, a common mistake by new users is that they forget to indent the body. If this is the case, make sure each statement meant to be included in the compound statement's body is indented at the same level under the compound statement's beginning. Here is the above example fixed:

>>> names = ['sarah', 'lucy', 'michael']
>>> for name in names:
...     print(name) # The for loop body is now correctly indented.
... 
sarah
lucy
michael

Another common case is that, for some reason, a user may not want to define an actual body for the compound statement, or the body may be commented out. In this case, the pass statement can be used. The pass statement can be used anywhere Python expects one or more statements as a placeholder. From the documentation for pass:

pass is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:

def f(arg): pass    # a function that does nothing (yet)

class C: pass       # a class with no methods (yet)

Here is the above example with the if statement fixed by using the pass keyword:

>>> if True:
...     pass # We don't want to define a body.
... 
>>>

What does "IndentationError: unindent does not match any outer indentation level" mean?

Problem

This error occurs when you unindent a statement, but now the indentation level of that statement does not match that of any former statement. For example, in the below code we unindent the second call to print. However, the indentation level does not match that of any former statement:

>>> if True:
...     if True:
...         print('yes')
...    print()
  File "<stdin>", line 4
    print()
          ^
IndentationError: unindent does not match any outer indentation level

This error is especially hard to catch because even one space will cause your code to fail.

Fix

The fix is to ensure that when you unindent a statement, the indentation level matches that of a former statement. Consider the above example once again. In the example, I want the second call to print to be in the first if statements body. So I need to make sure that that line's indentation level matches that of the former statements in the first if statement's body:

>>> if True:
...     if True:
...         print('yes')
...     print() # indentation level now matches former statement's level.
... 
yes

>>> 

I'm still getting an IndentationError but my program appears to be correctly indented. What do I do?

If your program visually appears to have correct indentation, but your still getting an IndentationError you have most likely mixed tabs with spaces. This will sometimes cause Python to raises strange errors. See the subsection Special cases under What does "TabError: inconsistent use of tabs and spaces in indentation" mean? for an more in-depth explanation of the problem.

What does "TabError: inconsistent use of tabs and spaces in indentation" mean?

Problem

This error only occurs when you attempt to mix tabs and spaces as indentation characters. As said above, Python will not allow your program to contain a mix of tabs and spaces, and will raise the specific exception TabError if it finds you have. For example, in the program below, a mix of tabs and spaces is used for indentation:

>>> if True:
...     if True:
...         print()
...     print()
...     print()
  File "<stdin>", line 5
    print()
          ^
TabError: inconsistent use of tabs and spaces in indentation

Here is a picture which visually shows the whitespace in the above program. Gray dots are spaces, and gray arrows are tabs:

We can see we have indeed mixed spaces and tabs for indentation.

Special cases

Note Python will not always raise a TabError if you mix tabs and spaces into your program. If the program indentation is unambiguous, Python will allow tabs and spaces to be mixed. For example:

>>> if True:
...     if True: # tab
...         pass # tab, then 4 spaces
... 
>>>

And sometimes Python simply chokes on the mixture of tabs and spaces and erroneously raises an IndentationError exception when a TabError would be more appropriate. Another example:

>>> if True:
...     pass # tab
...     pass # 4 spaces
  File "<stdin>", line 3
    pass # 4 spaces
                ^
IndentationError: unindent does not match any outer indentation level

As you can see, running your code this way can create mysterious errors. Even though the program visually appears to be fine, Python became confused trying to parse the tabs and spaces used for indention and errored out.

These are excellent examples that demonstrate why to never mix tabs and spaces and make use of the -t and -tt interpreter flags when using Python 2.

Fix

If your program is short, probably the easiest and quickest fix is to simply re-indent the program. Make sure each statement is indented by four spaces per indention level (see How do I indent my code?).

However, if you already have a large program that you've mixed tabs and spaces into, there are automated tools that can be used to convert all of your indentation to just spaces.

Many editors such as PyCharm and SublimeText have options to automatically convert tabs to spaces. There are also several on-line tools such as Tabs To Spaces or Browserling that allow you to quickly re-indent your code. There are also tools written in Python. autopep8 for example can automatically re-indent your code and other indentation errors as well.

Even the best tools though will sometimes not be able to fix all of your indentation errors and you'll have to fix them manually. That's why it's important to always properly indent your code from the start.

I'm still having a hard time with Python's indentation syntax. What do I do?

Don't get discouraged if you're still struggling. It can take time to get use to Python's whitespace syntax rules. Here are some tips to help:

  • Get an editor that will tell you when you have an indentation error. Some goods ones are as said above are, PyCharm, SublimeText, and Jupyter Notebook.
  • When you indent your code, count out loud to yourself how many times you press the space-bar (or tab key). For example, if you needed to indent a line by four spaces, you would say out loud "one, two, three, four" while simultaneously pressing the space-bar each time. It sounds silly, but it helps train your brain to think about how deep you're indenting your code.
  • If you have an editor, see if it has an option to automatically convert tabs to spaces.
  • View others' code. Browse github or Stackoverflow and see examples of Python code.
  • Just write code. That's the single best way to get better. The more you write Python code, the better you'll get.

Resources used

这篇关于我得到一个IndentationError。如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆