1

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
4

5 回答 5

6

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.

于 2012-12-28T11:52:28.243 回答
5
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
于 2012-12-28T11:53:39.973 回答
2

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.

于 2012-12-28T11:52:29.977 回答
2

Your code should look like:

def main():
    print "hello"

if __name__=='__main__':
    main()
于 2012-12-28T11:52:58.950 回答
0

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()
于 2022-01-17T22:53:06.723 回答