6

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

2
  • Pylint should point you at the line numbers. Commented May 13, 2015 at 12:59
  • 2
    Use an IDE supports Python indentation such as LiClips Commented May 13, 2015 at 13:02

4 Answers 4

7

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

Sign up to request clarification or add additional context in comments.

3 Comments

Hey, thanks very much. is there a tool that you would recommend for auto-indentation, not to fix but to auto-indent when writing a script?
@user3721640: Take a look at the huge list on wiki.python.org/moin/PythonEditors . Any decent text editor suitable for programming should be configurable to support Python, to some degree. However, while auto-indenting is easy, auto-dedenting isn't since the editor can't guess what you want your code to do. FWIW, I use often use Kate, the primary KDE editor, but I also use Geany.
@user3721640 Spyder works well for dedenting easily enough (shift-tab over a highlighted block or line).
3

You can use reindent.py.

For me, it worked on some files, but it didn't work on others. Give it a try.

Usage:

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.

Comments

1

You can use Spyder IDE

Source Menu -> Fix Indentation

enter image description here

Comments

-2

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

1 Comment

I think OP clearly knows what an IndentationError is. This answer is not really helpful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.