简体   繁体   中英

IndentationError expected an indented block

Here is the code:

def myfirst_yoursecond(p,q):

a = p.find(" ")
b = q.find(" ")
str_p = p[0:a]
str_q = p[b+1:]

if str_p == str_q:
    result = True
else:
    result = False
return result

Here is the error:

Traceback (most recent call last):
  File "vm_main.py", line 26, in <module>
    import main
  File "/tmp/vmuser_ssgopfskde/main.py", line 22
    result = False
         ^
IndentationError: expected an indented block

What's wrong with my code?

You've mixed tabs and spaces. This can lead to some confusing errors.

I'd suggest using only tabs or only spaces for indentation.

Using only spaces is generally the easier choice. Most editors have an option for automatically converting tabs to spaces. If your editor has this option, turn it on.


As an aside, your code is more verbose than it needs to be. Instead of this:

if str_p == str_q:
    result = True
else:
    result = False
return result

Just do this:

return str_p == str_q

You also appear to have a bug on this line:

str_q = p[b+1:]

I'll leave you to figure out what the error is.

This error also occurs if you have a block with no statements in it

For example:

def my_function():
    for i in range(1,10):


def say_hello():
    return "hello"

Notice that the for block is empty. You can use the pass statement if you want to test the remaining code in the module.

If you are using a mac and sublime text 3, this is what you do.

Go to your /Packages/User/ and create a file called Python.sublime-settings .

Typically /Packages/User is inside your ~/Library/Application Support/Sublime Text 3/Packages/User/Python.sublime-settings if you are using mac os x.

Then you put this in the Python.sublime-settings .

{
    "tab_size": 4,
    "translate_tabs_to_spaces": false
}

Credit goes to Mark Byer's answer , sublime text 3 docs and python style guide .

This answer is mostly for readers who had the same issue and stumble upon this and are using sublime text 3 on Mac OS X.

I got the same error, This is what i did to solve the issue.

Before Indentation:

在此处输入图片说明

Indentation Error: expected an indented block.

After Indentation:

在此处输入图片说明

Working fine. After TAB space.

You should install a editor (or IDE) supporting Python syntax. It can highlight source code and make basic format checking. For example: Eric4, Spyder, Ninjia, or Emacs, Vi.

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