簡體   English   中英

Python 錯誤“IndentationError:預期有縮進塊”

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

這是我的程序,我收到以下提到的錯誤:

def main():
    print "hello"

if __name__=='__main__':
main()

錯誤

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

您的縮進不正確。 嘗試這個 :

def main():
    print "hello"

if __name__=='__main__':
    main()

所有功能塊以及if-else循環塊都必須用制表符或4個空格(取決於環境)縮進。

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

請參閱以獲得一些說明。

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()

注意縮進。 行開頭的空白決定行的縮進級別,然后將其用於確定Python中語句的分組。

您的代碼應如下所示:

def main():
    print "hello"

if __name__=='__main__':
    main()

只是分享這種愚蠢。 我有一個非常相似的錯誤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