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.
Get Your Code: Click here to download the free sample code you’ll use to learn how to properly indent Python code.
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:
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.
Note: PEP 8 is the style guide for Python that was first introduced in 2001. Among other recommendations, it specifies that code indentation should be four spaces per indentation level. All environments discussed here follow that standard.
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:
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_numberto the integer value of7. - Line 2 starts a
forloop usingnumberas an iterator over a range of values from0to9. - Line 3 checks if
numberis equal tolucky_number. This line is indented to show it’s part of theforloop’s body. - Line 4 prints a message when the condition
number == lucky_numberisTrue. This line is indented to show it’s part of the body of theifstatement. - 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 theifstatement on line 3. - Line 6 prints a message when the condition
number == lucky_numberisFalse. This line is indented to show it’s part of the body of theelseclause. - Line 8 prints a final message. It’s de-indented to show it’s not part of the
forloop, but executes after theforloop is done.
If any part of this code is unfamiliar to you, you can learn more by exploring these resources:
- For more on
forloops, read PythonforLoops: The Pythonic Way. - For more on
range(), read Pythonrange(): Represent Numerical Ranges. - For more on
ifandelseclauses, read Conditional Statements in Python. - For more on the
print()function, read Your Guide to the Pythonprint()Function. - For more on f-string formatting, read Python’s F-String for String Interpolation and Formatting.
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.
You can see the same behavior in Visual Studio Code:
Both VS Code and PyCharm recognize Python code and automatically indent it whenever necessary. They also allow you to de-indent lines using Backspace or Shift+Tab.
Both Python IDLE and the Python REPL also automatically indent as appropriate, but they only respond to Backspace for de-indenting:
Notice that both the IDLE and REPL editors indicate a block not only with indentation but also with the ... prompt. You end the editor and execute the code by pressing Enter on a blank line.
Of course, you may need to indent or de-indent a line that the environment doesn’t handle automatically. Perhaps you’ve pasted in code from somewhere else, uncommented a line that needs to be part of a block, or indented a line accidentally. Many editors and code formatters handle this automatically, but you can also do it manually.
You can press Tab at the beginning of the line to indent it, or Shift+Tab to de-indent it:
You can even indent and de-indent multiple lines of code. Highlight all the lines you want to modify, then use Tab to indent them or Shift+Tab to de-indent them all at once.
Note: Other commonly supported keyboard shortcuts for handling indentation are Ctrl+] and Ctrl+[, which indent and de-indent code, respectively.
All of these environments do their best to keep your code properly formatted and syntactically correct. Next, you’ll look at environments that require more configuration to keep your Python code in good working order.
Extensible Editors
You may prefer doing all your editing in a general-purpose text editor, such as Emacs or Vim. These editors can be modified with extensions to support Python coding just like a dedicated IDE.
Emacs ships with a built-in Python mode—aptly named python-mode—which can be augmented and extended to provide a complete Python development experience. However, even if you don’t do anything, Emacs can automatically indent your Python code just like any dedicated IDE:
To de-indent a line as you type in Emacs, you can use either Backspace or Shift+Tab. To indent and de-indent selected lines, use Tab and Shift+Tab.
Vim also has built-in support for Python code and automatically indents lines as you type in Insert mode:
When inserting Python code, only pressing Backspace works to de-indent a line. However, the modal nature of Vim means you can also indent and de-indent code using Normal mode. In Normal mode, you indent the currently selected line using >+> and de-indent it using <+<. You can also auto-indent your code with =, followed by any motion key.
Next, you’ll learn how even simple text editors can be used to indent Python code.
Simple Text Editors
There may be times when you find yourself using a non-Python-aware or a non-extensible editor. You may be working directly on an embedded system, a phone or tablet with limited development tools, or an SSH session under a restricted account. In those cases, you may be limited to a simple text editor such as vi, nano, or Windows Notepad. When that happens, it’s important to know exactly what your text editor does when you press Tab.
Recall that indenting means adding spaces to the start of a line. Each IDE and Python-aware editor shown typically inserts a fixed number of spaces—usually four, per PEP 8—when you press Tab to indent. Likewise, when the cursor is in leading whitespace, pressing Shift+Tab or Backspace removes the same number of spaces to de-indent.
However, many simple text editors will insert tab characters—ASCII 0x09 or Unicode U+0009—which can resolve to any number of spaces. This can cause an IndentationError when Python attempts to read and parse the code.
For these basic text editors, it’s recommended to use Space to properly indent each line of your code, as shown in this example using nano:
Note that each indentation level uses the same number of space characters, namely four. This is consistent with most Python IDEs, Python-aware editors, and PEP 8 guidance. If you find yourself using a simple editor to modify existing Python code, you must match this spacing in your new code.
You can determine if a simple editor inserts spaces or tab characters when you press the Tab key using the following code:
while False:
pass
Type this code into your editor, using the Tab key to indent the second line. Then, press the Left key to move the cursor to the beginning of the second line. The cursor will jump over the whitespace if the editor inserts tab characters, as shown in nano:
As you move your cursor back and forth on that line, it jumps immediately from pass to the start of the line. To code Python in nano, you need to use Space and not Tab. Some editors offer the option to show individual whitespace characters, which can also help you differentiate between spaces and tabs. Consult your editor’s documentation to see if this option is available.
How to Use Code Formatters
Code formatters are tools that automatically format your Python code according to PEP 8, improving readability and maintainability over the long term. They can run inside your editor or from the command line, and can even be configured to run automatically.
Most Python IDEs have a formatting option built in, as do many Python-aware editors. In some cases, you may need to install a tool or plugin to enable and use this feature. Code formatting can help unify and normalize indentation in otherwise syntactically correct code.
Note: There are times when indentation isn’t needed syntactically but improves visual clarity. For example, a list may be spread over multiple lines if it exceeds the maximum line length:
long_indented_list.py
long_list_of_names = [
"Amy",
"Brian",
"Carol",
"Dennis",
"Emma",
"Frank",
"Georgia",
"Herbert",
"Isabelle",
"Joshua",
"Kimberly",
"Laurence",
"Megan",
"Nicolas",
"Ophelia",
]
Most code formatters will create or preserve this type of non-syntactic indentation.
Outside the editor, you have several options for code formatting tools. Three of the most popular are autopep8, Black, and Ruff. These tools help ensure your code conforms to the PEP 8 standards, including the four-space indentation convention and other style rules. They’re typically run from the command line but can also be incorporated into most IDEs and editors.
To see how they work, you can use the following Python code, which is syntactically correct but doesn’t conform to PEP 8 guidelines:
sample_code.py
def add(a, b):
answer = a + b
return answer
def sub (c ,
d):
answer = c -d
return answer
Running autopep8 won’t update the file automatically unless you provide the --in-place or -i option:
$ autopep8 -i sample_code.py
$ cat sample_code.py
def add(a, b):
answer = a + b
return answer
def sub(c,
d):
answer = c - d
return answer
$
Notice that autopep8 didn’t remove the extra whitespace in parameter lists for add() or sub(), since that might have been required for readability. You can apply other rules via command-line options to remove that whitespace.
Conversely, Black applies its rules and automatically writes those changes directly to the file:
$ black sample_code.py
reformatted sample_code.py
All done! ✨ 🍰 ✨
1 file reformatted.
$ cat sample_code.py
def add(a, b):
answer = a + b
return answer
def sub(c, d):
answer = c - d
return answer
$
Notice how Black removed the extra whitespace in the function parameter lists automatically.
The Ruff formatter is designed to be a drop-in replacement for Black and works similarly:
$ ruff format sample_code.py
1 file reformatted
$ cat sample_code.py
def add(a, b):
answer = a + b
return answer
def sub(c, d):
answer = c - d
return answer
$
Like Black, Ruff reformats the file in place and normalizes spacing and indentation. Ruff can also serve as a code linter using the ruff check command.
All three of these tools can be incorporated into most IDEs and Python editors to keep your code formatted properly. They also fit neatly into continuous integration and deployment (CI/CD) workflows.
Why Indent Python Code?
Throughout this tutorial, you’ve learned how to indent your Python code, but not why it’s important. In Python, indentation is part of the language’s syntax, used to determine the grouping of statements.
Statement grouping is an important part of every modern programming language and is used in many places:
- Loops need to know which statements to repeat.
- Conditionals need to know which statements to run when a condition is true or false.
- Function definitions need to know which statements to include in the function body.
Python uses the indentation level to determine which statements are in the same group. Contrast this with languages such as C, C++, and Java, which use { and } to mark the start and end of a group of statements. In those languages, indentation is used solely for visual clarity and code readability.
Conclusion
From dedicated Python IDEs to the most basic text editors, indenting Python code is a necessary technique to know and master.
In this tutorial, you learned:
- How to properly indent Python code in a variety of editors
- How your choice of editor can affect 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 can now confidently write Python code in any environment.
Get Your Code: Click here to download the free sample code you’ll use to learn how to properly indent Python code.
Frequently Asked Questions
Now that you have some experience with indenting code in Python, you can use the questions and answers below to check your understanding and recap what you’ve learned.
These FAQs are related to the most important concepts you’ve covered in this tutorial. Click the Show/Hide toggle beside each question to reveal the answer.
You use four spaces per indentation level to follow PEP 8 guidelines. Configure your editor so the Tab key inserts four spaces and never mixes tabs with spaces.
To de-indent a line, you press Backspace or Shift+Tab at the start of the line in most Python-aware editors. In IDLE and the REPL you use Backspace only. In Vim, you switch to Normal mode and type <<.
You use spaces in Python because mixing tabs and spaces can cause syntax errors. In simple editors that insert a tab character, configure them to insert spaces or type spaces manually.
To auto-format your code to fix indentation, you run a formatter like black, autopep8, or ruff from your editor or the command line. These tools apply PEP 8 rules and fix inconsistent indentation automatically.
Python uses indentation to define code blocks for loops, conditionals, and function bodies. When you change the indentation, you change which statements run together.



