How to Use Indentation in Python Programming

By John Paul Mueller

As you work through examples of Python programming, you see that certain lines are indented. In fact, you will also see a fair amount of white space (such as extra lines between lines of code). Python ignores any indentation in your application. The main reason to add indentation is to provide visual cues about your code. Indentation in code shows the relationships between various code elements.

The various uses of indentation will become more familiar as you gain more experience with Python. However, it’s important to know at the outset why indentation is used and how it gets put in place. So, it’s time for another example. The following steps help you create a new example that uses indentation to make the relationship between application elements a lot more apparent and easier to figure out later.

  1. Choose File→New File.

    IDLE creates a new Edit window for you.

  2. Type print(“This is a really long line of text that will ” +.

    You see the text displayed normally onscreen, just as you expect. The plus sign (+) tells Python that there is additional text to display. Adding text from multiple lines together into a single long piece of text is called concatenation.

  3. Press Enter.

    image0.jpg

    The insertion point doesn’t go back to the beginning of the line, as you might expect. Instead, it ends up directly under the first double quote. This feature is called automatic indention and it’s one of the features that differentiates a regular text editor from one designed to write code.

  4. Type “appear on multiple lines in the source code file.”) and press Enter.

    Notice that the insertion point goes back to the beginning of the line. When IDLE senses that you have reached the end of the code, it automatically outdents the text to its original position.

  5. Choose File→Save.

    You see the Save As dialog box.

  6. Type LongLine.py in the File Name field and click Save to save it.

  7. Choose Run→Run Module.

    A new Python Shell window opens with the text displayed. Even though the text appears on multiple lines in the source code file, it appears on just one line in the output.

    image1.jpg