为什么我会得到“IndentationError:expected an indented block”?

2024-05-23 17:56:04 发布

您现在位置: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)

我得到:

        elif index == "" :
        ^
    IndentationError: expected an indented block

Tags: importindexlenifossysrestorefiles
3条回答

实际上,关于Python中的缩进,您需要了解的内容有很多:

Python非常关心缩进。

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

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

有不同的缩进错误,阅读这些错误会有很大帮助:

1缩进错误:需要缩进的块“

有两个主要原因会导致您出现这样的错误:

-您有一个“:”后面没有缩进的块。

下面是两个例子:

示例1,无缩进块:

输入:

if 3 != 4:
    print("usual")
else:

输出:

  File "<stdin>", line 4

    ^
IndentationError: expected an indented block

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

示例2,未缩进块:

输入:

if 3 != 4:
print("usual")

输出

  File "<stdin>", line 2
    print("usual")
        ^
IndentationError: expected an indented block

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

-您使用的是Python2.x,它混合了制表符和空格:

输入

def foo():
    if 1:
        print 1

请注意,如果之前有制表符,打印之前有8个空格。

输出:

  File "<stdin>", line 3
    print 1
      ^
IndentationError: expected an indented block

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

  • 你可以得到一些信息。
  • 删除所有选项卡并用四个空格替换它们。
  • 并将编辑器配置为自动执行此操作。

2缩进错误:意外缩进“

缩进块很重要,但只缩进应该缩进的块。 所以基本上这个错误说:

-前面有一个没有“:”的缩进块。

示例:

输入:

a = 3
  a += 3

输出:

  File "<stdin>", line 2
    a += 3
    ^
IndentationError: unexpected indent

输出表明他不需要缩进块行2,然后应该将其删除。

3。”TabError:缩进“中不一致地使用制表符和空格(仅限python3.x)

  • 你可以得到一些信息。
  • 但基本上,您在代码中使用了制表符和空格。
  • 你不想那样。
  • 删除所有选项卡并用四个空格替换它们。
  • 并将编辑器配置为自动执行此操作。


最后,回到你的问题上来:

只需查看错误的行号,然后使用前面的信息修复它。

如错误消息所示,您有一个缩进错误。这可能是由标签和空格的混合造成的。

我遇到了同样的问题,并发现(通过this answer to a similar question)问题是我没有正确缩进docstring。不幸的是,IDLE在这里没有给出有用的反馈,但是一旦我修复了docstring缩进,问题就消失了。

特别是---产生缩进错误的错误代码:

def my_function(args):
"Here is my docstring"
    ....

避免缩进错误的好代码:

def my_function(args):
    "Here is my docstring"
    ....

注意:我不是说这是问题所在,但它可能是问题所在,因为在我的情况下,它是问题所在!

相关问题 更多 >