How to Indent and Dedent Your Python Code

By Brendan Scott

You’re going to have to change the number of spaces in front of one or more lines of code. It’s common in programming like Python. Moving them in is indenting. Moving them out is dedenting (or deindenting).

For example, if you want to move a print statement from the main part of the program into the code block of a loop, you need to indent it. To move it out of the code block of a loop, you need to deindent it. IDLE has tools to indent and dedent code blocks.

Try those -denting tools:

  1. Start with some code.

    Here’s some:

    ""This is just a test file""
    DEBUG = True
    print('Hello World! from the editor') # hashes are used for comments too
    "" You usually use hashes at the end of a line
    rather than for a block comment like this one.
    ""
    ###############################################################
    # Nevertheless you can still use hashes for block comments
    # Especially if you want to have a specific visual effect
    ###############################################################
    if DEBUG:
        print('I think I need another print statement in this code block')
    print('See that the comments were ignored?') # even this one
  2. Select the lines to indent.

    Click and drag with your mouse to select the code (the last print statement), or press Shift while using your arrow keys.

  3. Choose Format → Indent Region.

    Ctrl+] also works.

  4. Make sure the code’s indented into a valid code block.

    Indentation is meaningful to Python. You’ll get a syntax error if you have the wrong level of indent.

    It’s best to use four spaces of indent for each code block level. If you use another number of spaces (2, 6, 8), that’s fine. The important thing is that all the code in the code block must have the same number of spaces.

    To go the other way, select the code and choose File → Dedent Region (or press Ctrl+[).