Python 为什么我会收到“IndentationError:期望一个缩进块”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4446366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:46:52  来源:igfitidea点击:

Why am I getting "IndentationError: expected an indented block"?

python

提问by ParoX

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)

I am getting:

我正进入(状态:

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

采纳答案by mpen

As the error message indicates, you have an indentation error. It is probably caused by a mix of tabs and spaces.

如错误消息所示,您有缩进错误。这可能是由制表符和空格混合引起的。

回答by user3317399

You might want to check you spaces and tabs. A tab is a default of 4 spaces. However, your "if" and "elif" match, so I am not quite sure why. Go into Options in the top bar, and click "Configure IDLE". Check the Indentation Width on the right in Fonts/Tabs, and make sure your indents have that many spaces.

您可能想要检查空格和制表符。一个制表符默认为 4 个空格。但是,您的“if”和“elif”匹配,所以我不太确定为什么。进入顶部栏中的选项,然后单击“配置空闲”。检查字体/标签右侧的缩进宽度,并确保您的缩进有那么多空格。

回答by maxomai

I had this same problem and discovered (via this answer to a similar question) that the problem was that I didn't properly indent the docstring properly. Unfortunately IDLE doesn't give useful feedback here, but once I fixed the docstring indentation, the problem went away.

我遇到了同样的问题并发现(通过这个对类似问题的回答)问题是我没有正确缩进文档字符串。不幸的是,IDLE 没有在这里提供有用的反馈,但是一旦我修复了文档字符串缩进,问题就消失了。

Specifically --- bad code that generates indentation errors:

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

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

Good code that avoids indentation errors:

避免缩进错误的好代码:

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

Note: I'm not saying this isthe problem, but that it might be, because in my case, it was!

注意:我并不是说这问题所在,但可能是,因为在我的情况下,确实如此!

回答by Xavier C.

There are in fact multiples things you need to know about indentation in Python:

实际上,关于 Python 中的缩进,您需要了解很多事情:

Python really cares about indention.

Python 真的很关心缩进。

In a lot of other languages the indention is not necessary but improves readability. In Python indentation replaces the keyword begin / endor { }and is therefore necessary.

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

This is verified before the execution of the code, therefore even if the code with the indentation error is never reached, it won't work.

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

There are different indention errors and you reading them helps a lot:

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

1. "IndentationError: expected an indented block"

1.“IndentationError:需要一个缩进块”

They are two main reasons why you could have such an error:

它们是您可能出现此类错误的两个主要原因:

- You have a ":" without an indented block behind.

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

Here are two examples:

这里有两个例子:

Example 1, no indented block:

示例 1,无缩进块:

Input:

输入:

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

Output:

输出:

  File "<stdin>", line 4

    ^
IndentationError: expected an indented block

The output states that you need to have an indented block on line 4, after the else:statement

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

Example 2, unindented block:

示例 2,未缩进的块:

Input:

输入:

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

Output

输出

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

The output states that you need to have an indented block line 2, after the if 3 != 4:statement

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

- You are using Python2.x and have a mix of tabs and spaces:

- 您正在使用 Python2.x 并混合使用制表符和空格:

Input

输入

def foo():
    if 1:
        print 1

Please note that before if, there is a tab, and before print there is 8 spaces.

请注意,if 之前有一个制表符,print 之前有 8 个空格。

Output:

输出:

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

It's quite hard to understand what is happening here, it seems that there is an indent block... But as I said, I've used tabs and spaces, and you should never do that.

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

  • You can get some info here.
  • Remove all tabs and replaces them by four spaces.
  • And configure your editor to do that automatically.
  • 你可以在这里得到一些信息。
  • 删除所有选项卡并用四个空格替换它们。
  • 并配置您的编辑器以自动执行此操作。

2. "IndentationError: unexpected indent"

2.“IndentationError:意外缩进”

It is important to indent blocks, but only blocks that should be indent. So basically this error says:

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

- You have an indented block without a ":" before it.

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

Example:

例子:

Input:

输入:

a = 3
  a += 3

Output:

输出:

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

The output states that he wasn't expecting an indent block line 2, then you should remove it.

输出表明他不希望缩进块第 2 行,那么您应该将其删除。

3. "TabError: inconsistent use of tabs and spaces in indentation"(python3.x only)

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

  • You can get some info here.
  • But basically it's, you are using tabs and spaces in your code.
  • You don't want that.
  • Remove all tabs and replaces them by four spaces.
  • And configure your editor to do that automatically.
  • 你可以在这里得到一些信息。
  • 但基本上是这样,您在代码中使用了制表符和空格。
  • 你不想那样。
  • 删除所有选项卡并用四个空格替换它们。
  • 并配置您的编辑器以自动执行此操作。



最后,回到你的问题:

Just look at the line number of the error, and fix it using the previous information.

只需查看错误的行号,并使用先前的信息修复它。

回答by Rad Apdal

This is just an indentation problem since Python is very strict when it comes to it.

这只是一个缩进问题,因为 Python 在这方面非常严格。

If you are using Sublime, you can select all, click on the lower right beside 'Python' and make sure you check 'Indent using spaces' and choose your Tab Width to be consistent, then Convert Indentation to Spaces to convert all tabs to spaces.

如果您使用Sublime,则可以全选,单击“Python”旁边的右下角并确保选中“使用空格缩进”并选择制表符宽度以保持一致,然后将缩进转换为空格以将所有制表符转换为空格.

回答by Haseeb Pervaiz

in python intended block mean there is every thing must be written in manner in my case I written it this way

在python预期块中意味着在我的情况下,每件事都必须以这种方式编写

 def btnClick(numbers):
 global operator
 operator = operator + str(numbers)
 text_input.set(operator)

Note.its give me error,until I written it in this way such that "giving spaces " then its giving me a block as I am trying to show you in function below code

注意。它给我错误,直到我以这种方式编写它“给空格”然后它给我一个块,因为我试图在代码下面的函数中向你展示

def btnClick(numbers):
___________________________
|global operator
|operator = operator + str(numbers)
|text_input.set(operator)