简体   繁体   中英

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 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.

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".

def some_function():
    # some_code
    # return

def main():
    print "hello"

if __name__=='__main__':
    main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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