Search code examples
pythonif-statementindentationauto-indent

Avoiding indentation in Python else and elif


In writing a Python code in Wing or IDLE, inside the if condition, we must have an indentation for each line. But the else and the elif part must be aligned with if. However when I type else: or elif: in a newline, it has an indentation and I must remove it manually. I have seen it in several IDEs like Wing.

Is there any way to avoid indentation for else and elif? Indeed I need this:

if (condition):
    do this
else:
    do this

But when I type it, it's like:

if (condition)
    do this
    else:
    do this

Solution

  • You seem to believe the editor will somehow know how many lines the indented suites of code should have.

    It would be easy to make editors "outdent" if those suites were all one line, but a cursory inspection of any moderately complex Python program will show that is clearly not the case.

    Which means it's up to us to indicate the end by outdenting manually, usually with SHIFT-TAB, at the end of the clause.