Auto correct indentation errors in Python

本小妞迷上赌 提交于 2021-02-10 23:41:13

问题


I am trying fix some indentation errors in a Python script. Is there a way to auto correct the errors online or using other utilities?

I hope this error is very familiar, but wanted to avoid this again. Does any editor help in fixing these issues?

IndentationError: expected an indented block


回答1:


It's not possible in general because some cases would be ambiguous:

something = foo()
if something:
    something.bar()
  print("ok") # Only half indented. Should this be inside or outside of the if statement?

It's much better to find an editor with auto-indentation support and make sure you indent properly (even in languages without significant whitespaces, as it makes your code easier to read).




回答2:


You can use reindent.py

For me it worked on some files but it didin't work on others.Give it a try. reindent.py

Uasge:

reindent.py <filename>.py

Change Python (.py) files to use 4-space indents and no hard tab characters.

Also trim excess spaces and tabs from ends of lines, and remove empty lines at the end of files.




回答3:


You can use Spyder IDE

Source Menu -> Fix Indentation




回答4:


This particular error usually occurs when you forget to add an indented block after a statement that needs one (i.e. if or for). You likely forgot to indent the required block or accidentally hit backspace (or something) such as

def sayhello():
print "Hello world!"

Sometimes you don't want any code after an if statement or after try/except statements, but python will require at least one line after them, so you can use the pass keyword

try:
    x= 4/0
except:
    pass

print x


来源:https://stackoverflow.com/questions/30215496/auto-correct-indentation-errors-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!