Vikash
Vikash

Reputation: 459

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

Upvotes: 1

Views: 17827

Answers (5)

asheeshr
asheeshr

Reputation: 4114

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 four spaces (depending on environment).

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

Refer to 2.1.8 Indentation for some explanation.

Upvotes: 6

questionto42
questionto42

Reputation: 9512

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

Upvotes: 0

ATOzTOA
ATOzTOA

Reputation: 35950

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 it is 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

Upvotes: 5

avasal
avasal

Reputation: 14854

Your code should look like:

def main():
    print "hello"

if __name__=='__main__':
    main()

Upvotes: 3

Faruk Sahin
Faruk Sahin

Reputation: 8726

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.

Upvotes: 2

Related Questions