Search code examples
pythonpython-3.xpython-idle

Reverse Tab in Python IDLE (3.7)


Is there a keyboard shortcut for reverse-tab in the Python IDLE?

I am trying to write an if-elif-else statement but cannot reverse-tab to properly indent the elif statement. I've tried shift+tab and shift+ctrl+tab.

For example, I can write this...

if x < 0:
    print('Less than Zero')

but when I try to add the elif statement...

elif x == 0:
    print('Zero')

I get the following error message:

SyntaxError: unindent does not match any outer indentation level        

Solution

  • Use the back space key to dedent. It is easiest if one does so before entering any code. If there is already code on the line, put the edit cursor between the end of the indent and the beginning of the code before hitting backspace. Note that in IDLE, one enters and edits, and submits complete statements for execution. Hence no secondary prompts. Example:

    >>> a, x, y = 1, 2, 3  # Bind some names.  This is one statement.
    >>> if a:  # When you hit return, IDLE see that you entered the header
               # of a compound statement and indents the next line with a Tab.
               # Note that I have to use 8 spaces here instead of a tab.
            print(x)  # When you hit return, IDLE keeps the same indent.
                      # Use Backspace [<--] to dedent back to the margin.
    else:   # Do not line up 'else' with 'if' by adding 4 spaces.
            # Since this is another header, an indent is added on the next line.
            print(y)  # No header, indent kept the same.
            # Hit Return to enter blank line
    

    The final blank line signals that the compound statement is complete and should be executed. Until then, one can edit any part of the statement.

    I am a bit stunned that 3 people would suggest the awkward and much harder workaround of selecting the line or at least the indent and using control-[. I am thinking about how to make the easy way more obvious.

    I am aware that having 'if', 'elif', and 'else' not lined up is a nuisance. I intend to fix this.