Python error“IndentationError:应为缩进块”

2024-06-15 23:34:59 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的程序,我得到以下提到的错误:

def main():
    print "hello"

if __name__=='__main__':
main()

错误

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

Tags: namepy程序anhelloifmaindef
3条回答
Normal Code
    Indent block
    Indent block
        Indent block 2
        Indent block 2

你应该:

def main():
    print "hello"

if __name__=='__main__':
    main()

它可以是空格或制表符。

此外,缩进不需要在整个文件中相同,而只需要在每个块中相同。

例如,您可以使用这样的工作文件,但不推荐使用。

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

你的压痕掉了。试试这个:

def main():
    print "hello"

if __name__=='__main__':
    main()

所有功能块以及循环块都必须缩进一个制表符或4个空格(取决于环境)。

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

有关一些解释,请参阅this

你可能想要这样的东西:

def main():
    print "hello"

if __name__=='__main__':
    main()

注意凹痕。行首的前导空格决定行的缩进级别,然后用于确定Python中语句的分组。

相关问题 更多 >