为什么我会收到"IndentationError:期望缩进块"?

Par*_*roX 50 python

if len(trashed_files) == 0 :
    print "No files trashed from current dir ('%s')" % os.path.realpath(os.curdir)
else :
    index=raw_input("What file to restore [0..%d]: " % (len(trashed_files)-1))
    if index == "*" :
        for tfile in trashed_files :
            try:
                tfile.restore()
            except IOError, e:
                import sys
                print >> sys.stderr, str(e)
                sys.exit(1)
    elif index == "" :
        print "Exiting"
    else :
        index = int(index)
        try:
            trashed_files[index].restore()
        except IOError, e:
            import sys
            print >> sys.stderr, str(e)
            sys.exit(1)
Run Code Online (Sandbox Code Playgroud)

我正进入(状态:

        elif index == "" :
        ^
    IndentationError: expected an indented block
Run Code Online (Sandbox Code Playgroud)

mpe*_*pen 67

如错误消息所示,您有缩进错误.它可能是由标签和空格的混合引起的.

  • 我想的第一件事,所以我将所有标签转换为4个空格. (5认同)

Xav*_* C. 28

实际上,您需要了解Python中缩进的多项内容:

Python非常关心缩进.

在许多其他语言中,缩进不是必需的,但提高了可读性.在Python缩进中替换关键字begin / end{ }因此是必要的.

这在代码执行之前得到验证,因此即使具有缩进错误的代码永远不会到达,它也无法工作.

有不同的缩进错误,你阅读它们有很大帮助:

1."IndentationError:预期缩进块"

它们是导致此类错误的两个主要原因:

- 你有一个":",后面没有缩进块.

这是两个例子:

例1,没有缩进块:

输入:

if 3 != 4:
    print("usual")
else:
Run Code Online (Sandbox Code Playgroud)

输出:

  File "<stdin>", line 4

    ^
IndentationError: expected an indented block
Run Code Online (Sandbox Code Playgroud)

输出表明您需要在else:语句后面有一个缩进的块行4

例2,未缩进块:

输入:

if 3 != 4:
print("usual")
Run Code Online (Sandbox Code Playgroud)

产量

  File "<stdin>", line 2
    print("usual")
        ^
IndentationError: expected an indented block
Run Code Online (Sandbox Code Playgroud)

输出表明您需要在if 3 != 4:语句后面有一个缩进的块行2

- 您正在使用Python2.x并且有多个制表符和空格:

输入

def foo():
    if 1:
        print 1
Run Code Online (Sandbox Code Playgroud)

请注意,之前是否有标签,打印前有8个空格.

输出:

  File "<stdin>", line 3
    print 1
      ^
IndentationError: expected an indented block
Run Code Online (Sandbox Code Playgroud)

很难理解这里发生了什么,似乎有一个缩进块...但正如我所说,我使用了制表符和空格,你永远不应该这样做.

  • 你可以在这里获得一些信息.
  • 删除所有选项卡并将其替换为四个空格.
  • 并配置您的编辑器自动执行此操作.

2."IndentationError:意外缩进"

缩进块很重要,但只有缩进块才有.所以基本上这个错误说:

- 你有一个缩进的块,前面没有":".

例:

输入:

a = 3
  a += 3
Run Code Online (Sandbox Code Playgroud)

输出:

  File "<stdin>", line 2
    a += 3
    ^
IndentationError: unexpected indent
Run Code Online (Sandbox Code Playgroud)

输出表明他不期望缩进块行2,然后你应该删除它.

3."TabError:缩进中选项卡和空格的使用不一致"(仅限python3.x)

  • 你可以在这里获得一些信息.
  • 但基本上,你在代码中使用制表符和空格.
  • 你不希望这样.
  • 删除所有选项卡并将其替换为四个空格.
  • 并配置您的编辑器自动执行此操作.


最后,回到你的问题:

只需查看错误的行号,并使用以前的信息进行修复.


归档时间:

查看次数:

373121 次

最近记录:

6 年,4 月 前