简体   繁体   English

Python 错误“IndentationError:预期有缩进块”

[英]Python error "IndentationError: expected an indented block"

This is my program and I am getting the following mentioned error:这是我的程序,我收到以下提到的错误:

def main():
    print "hello"

if __name__=='__main__':
main()

Error错误

  File "hello.py", line 8
    main()
    ^
IndentationError: expected an indented block

Your indentation is off. 您的缩进不正确。 Try this : 尝试这个 :

def main():
    print "hello"

if __name__=='__main__':
    main()

All function blocks, as well as if-else, looping blocks have to be indented by a tab or 4 spaces (depending on environment). 所有功能块以及if-else循环块都必须用制表符或4个空格(取决于环境)缩进。

if condition :
    statements  //Look at the indentation here
    ...
Out-of-block //And here

Refer to this for some explanation. 请参阅以获得一些说明。

Normal Code
    Indent block
    Indent block
        Indent block 2
        Indent block 2

You should do: 你应该做:

def main():
    print "hello"

if __name__=='__main__':
    main()

It can be either spaces or tabs. 它可以是空格或制表符。

Also, the indentation does NOT need to be same across the file, but only for each block. 同样,缩进不需要在文件中相同,而仅对于每个块而言。

For example, you can have a working file like this, but NOT recommended. 例如,您可以有一个这样的工作文件,但不建议这样做。

print "hello"
if True:
[TAB]print "a"
[TAB]i = 0
[TAB]if i == 0:
[TAB][SPACE][SPACE]print "b"
[TAB][SPACE][SPACE]j = i + 1
[TAB][SPACE][SPACE]if j == 1:
[TAB][SPACE][SPACE][TAB][TAB]print "c

You probably want something like: 您可能想要类似的东西:

def main():
    print "hello"

if __name__=='__main__':
    main()

Pay attention to the indentations. 注意缩进。 Leading whitespace at the beginning of a line determines the indentation level of the line, which then is used to determine the grouping of statements in Python. 行开头的空白决定行的缩进级别,然后将其用于确定Python中语句的分组。

Your code should look like: 您的代码应如下所示:

def main():
    print "hello"

if __name__=='__main__':
    main()

Just sharing this stupidity.只是分享这种愚蠢。 I had a very similar error IndentationError: expected an indented block def main() since I had commented out the whole body of a previous "some_function".我有一个非常相似的错误IndentationError: expected an indented block def main()因为我已经注释掉了以前的“some_function”的整个主体。

def some_function():
    # some_code
    # return

def main():
    print "hello"

if __name__=='__main__':
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM