How to Properly Indent Python Code

Knowing how to properly indent Python code is a key skill for becoming an accomplished Python developer. Beginning Python programmers know that indentation is required, but learning to indent code so it’s readable, syntactically correct, and easy to maintain is a skill that takes practice.

By the end of this tutorial, you’ll know:

  • How to properly indent Python code in a variety of editors
  • How your choice of editor can impact your Python code
  • How to indent code using spaces in simple text editors
  • How to use code formatters to properly indent Python code automatically
  • Why indentation is required when writing Python code

With this knowledge, you’ll be able to write Python code confidently in any environment.

How to Indent Code in Python

Indenting your code means adding spaces to the beginning of a line, which shifts the start of the line to the right, as shown below:

Python
number = 7
if number > 0:
    print("It's a positive number")

In this example, the first two lines aren’t indented, while the third line is indented.

How you indent your Python code depends on your coding environment. Most editors and integrated development environments (IDEs) can indent Python code correctly with little to no input from the user. You’ll see examples of this in the sections that follow.

Python-Aware Editors

In most cases, you’ll be working in a Python-aware environment. This might be a full Python IDE such as PyCharm, a code editor like Visual Studio Code, the Python REPL, IPython, IDLE, or even a Jupyter notebook. All these environments understand Python syntax and indent your code properly as you type.

Here’s a small example to show this automatic indentation. You’ll use the following code to see how each environment automatically indents as you type:

Python
lucky_number.py
 1lucky_number = 7
 2for number in range(10):
 3    if number == lucky_number:
 4        print("Found the lucky number!")
 5    else:
 6        print(f"{number} is not my lucky number.")
 7
 8print("Done.")

This example shows how indenting happens automatically and how to de-indent a line of code. De-indenting—also called dedenting—means removing spaces at the beginning of a line, which moves the start of the line to the left. The code on lines 5 and 8 needs to be de-indented relative to the previous lines to close the preceding code blocks. For a detailed explanation of the indentation in this code, expand the collapsible section below.

The code above shows different levels of indentation, combining a for loop with an if statement:

  • Line 1 initializes the variable lucky_number to the integer value of 7.
  • Line 2 starts a for loop using number as an iterator over a range of values from 0 to 9.
  • Line 3 checks if number is equal to lucky_number. This line is indented to show it’s part of the for loop’s body.
  • Line 4 prints a message when the condition number == lucky_number is True. This line is indented to show it’s part of the body of the if statement.
  • Line 5 provides a way to act when the condition on line 3 is False. This line is de-indented to show it’s part of the if statement on line 3.
  • Line 6 prints a message when the condition number == lucky_number is False. This line is indented to show it’s part of the body of the else clause.
  • Line 8 prints a final message. It’s de-indented to show it’s not part of the for loop, but executes after the for loop is done.

If any part of this code is unfamiliar to you, you can learn more by exploring these resources:

Each line of the code above exists at a specific indentation level. All consecutive statements at the same indentation level are considered to be part of the same group or code block. The table below shows each line of code from the example, its indentation level, and what action is needed to achieve that level:

Code Indentation Level Action
lucky_number = 7 0
for number in range(10): 0
if number == lucky_number: 1 Indent
print("Found the lucky number!") 2 Indent
else: 1 De-indent
print(f"{number} is not my lucky number.") 2 Indent
print("Done.") 0 De-indent

First, here’s what it looks like to enter this code in PyCharm, a full-featured Python IDE:

Notice that as you hit Enter on line 2, PyCharm immediately indents line 3 for you. The same thing happens on line 4. However, to de-indent line 5 and line 8, you have to either press Backspace or Shift+Tab to move the cursor back to the proper position for the next line.

Read the full article at https://realpython.com/how-to-indent-in-python/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Liked Liked