Python Indentation Made Simple: A Beginner’s Guide

Updated on: May 8, 2026
Reading time: 6 minutes
Homem pensando à frente de um notebook com código de programação

When you start learning Python, one concept appears almost immediately: indentation. Many beginners feel confused when they see spaces changing how the code works.

In Python, indentation is not just for visual organization. It is part of the language syntax itself. If your indentation is wrong, your program may stop working completely.

The good news is that Python indentation is actually simple once you understand the basics. In this guide, you will learn what indentation means, why it matters, common mistakes, and how to use it correctly in real projects.

If you are new to programming, you may also enjoy reading Python for Beginners and how programming works.

What Is Indentation in Python?

Indentation means adding spaces at the beginning of a line of code.

In many programming languages, indentation is optional and mostly improves readability. In Python, indentation defines blocks of code.

For example:

Python
if True:
    print("Hello")

The second line is indented with four spaces. This tells Python that the print() function belongs to the if statement.

Without indentation, Python would not understand which code belongs inside the condition.

Important: Python officially recommends using four spaces for indentation.

You can learn more about official Python style recommendations in the PEP 8 style guide.

Why Python Uses Indentation

Python was designed to be clean and easy to read.

Many other languages use symbols like curly braces { } to define code blocks. Python uses indentation instead.

Compare these examples:

Python Example

Python
if age >= 18:
    print("Adult")

Another Language Example

Python
if (age >= 18) {
    print("Adult");
}

Python removes extra symbols and focuses on readability.

This makes Python easier for beginners and also helps teams maintain cleaner code.

If you want to understand Python syntax better, check if, elif and else in Python.

How Indentation Works in Practice

Indentation usually appears after statements that end with a colon :.

Common examples include:

  • if statements
  • for loops
  • while loops
  • functions
  • classes
  • try blocks

Example using a loop:

Python
for number in range(3):
    print(number)

The indented line belongs to the loop.

If you add more indented lines, they also become part of the loop block.

Python
for number in range(3):
    print(number)
    print("Loop running")

After the indentation ends, Python understands that the block is finished.

Python
for number in range(3):
    print(number)

print("Loop finished")

The last line runs after the loop completes.

You can practice loops further in for loops in Python and while loops in Python.

Common Indentation Errors

Indentation mistakes are very common for beginners.

Here are the most frequent errors.

Missing Indentation

Python
if True:
print("Hello")

This causes an error because the second line should be indented.

Unexpected Indentation

Python
print("Start")
    print("Wrong")

Python sees unnecessary indentation and raises an error.

Mixing Tabs and Spaces

This is one of the most frustrating mistakes.

Some editors insert tabs while others insert spaces. Mixing both can create errors that are hard to spot.

Modern editors like Visual Studio Code automatically help prevent this issue.

Tip: Configure your editor to use spaces instead of tabs.

Understanding Nested Indentation

Nested indentation happens when one block exists inside another block.

Example:

Python
age = 20

if age >= 18:
    print("Adult")

    if age >= 65:
        print("Senior")

The second if statement is inside the first one.

Each indentation level adds structure to the code.

Beginners sometimes get lost with deeply nested blocks. Try to keep your code simple whenever possible.

If your code becomes difficult to read, consider splitting logic into functions.

You can learn more in functions in Python.

Best Practices for Python Indentation

Following consistent formatting makes your code easier to understand.

Here are some important best practices.

Use Four Spaces

Python developers usually use four spaces per indentation level.

Example:

Python
if True:
    print("Correct indentation")

Do Not Mix Tabs and Spaces

Choose one style and stay consistent.

Most developers prefer spaces.

Keep Nested Blocks Simple

Too many indentation levels make code harder to read.

Instead of this:

Python
if True:
    if True:
        if True:
            print("Too deep")

Try reorganizing your logic into functions.

Use a Good Code Editor

Modern editors automatically format indentation.

Popular choices include:

  • VS Code
  • PyCharm
  • IDLE

You can explore the best Python IDEs and Python IDLE.

Indentation in Functions and Classes

Functions and classes also depend on indentation.

Function Example

Python
def greet():
    print("Hello")

The indented line belongs to the function.

Without indentation, Python raises an error.

Class Example

Python
class Person:
    def __init__(self, name):
        self.name = name

Notice that methods inside the class are indented.

The code inside methods receives another indentation level.

If you want deeper knowledge, read object-oriented programming in Python.

Real-World Example of Python Indentation

Let’s look at a simple login system example.

Python
username = input("Username: ")
password = input("Password: ")

if username == "admin":
    if password == "1234":
        print("Login successful")
    else:
        print("Wrong password")
else:
    print("User not found")

This example shows how indentation controls program flow.

Indentation LevelPurpose
No indentationMain program flow
First levelInside first condition
Second levelInside nested condition

Without correct indentation, this program would fail.

How Beginners Can Avoid Indentation Problems

Most indentation issues happen because beginners type code manually without understanding the structure.

Here are practical ways to avoid problems.

  1. Use an editor with syntax highlighting.
  2. Enable automatic formatting.
  3. Always use four spaces.
  4. Avoid copying code from poorly formatted websites.
  5. Practice reading indentation visually.

Many editors also show vertical guides for indentation levels.

This makes nested blocks easier to understand.

If you are learning Python fundamentals, you may also enjoy common Python beginner mistakes.

Python Indentation vs Other Programming Languages

Some beginners coming from other languages find Python indentation unusual at first.

Here is a quick comparison:

LanguageUses Indentation as Syntax?Uses Braces?
PythonYesNo
JavaScriptNoYes
JavaNoYes
C++NoYes

Although it may feel strange initially, many developers later prefer Python’s cleaner style.

Readable code becomes easier to maintain and debug.

Conclusion

Python indentation is one of the language’s most important features.

Instead of using symbols like braces, Python uses spaces to define code blocks. This improves readability and encourages cleaner code.

At first, indentation errors can feel frustrating. However, after some practice, indentation becomes natural.

The key points to remember are simple:

  • Use four spaces
  • Stay consistent
  • Do not mix tabs and spaces
  • Keep nested blocks readable

Once you master indentation, writing Python code becomes much easier.

To continue learning, you can also explore essential Python commands and Python PEP 8 style guide basics.

Perguntas Frequentes (FAQ)

1. What is indentation in Python?

Indentation means adding spaces at the beginning of lines to define code blocks.

2. Why is indentation important in Python?

Python uses indentation to organize and execute code correctly.

3. How many spaces should I use?

Python recommends using four spaces per indentation level.

4. Can I use tabs instead of spaces?

Yes, but mixing tabs and spaces can create errors.

5. What happens if indentation is wrong?

Python raises an indentation error and stops the program.

6. Which statements require indentation?

Statements like if, for, while, functions, and classes need indentation.

7. Is indentation unique to Python?

Most languages use braces instead. Python uses indentation directly.

8. How can I avoid indentation errors?

Use a modern code editor with automatic formatting.

9. Does indentation improve readability?

Yes. Proper indentation makes code easier to understand.

10. Can nested indentation become a problem?

Yes. Too many nested blocks make code harder to read.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    Introdução ao módulo sys para iniciantes em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python sys Module for Beginners

    Learn Python's sys module: check Python version, read command-line args with sys.argv, manage sys.path, use sys.exit(), and measure object size.

    Ler mais

    Tempo de leitura: 3 minutos
    03/06/2026
    Uso do with para abrir arquivos com segurança em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python with Statement: Safe File Handling

    Learn how Python's with statement safely opens files: automatic close, read/write modes, CSV handling, multiple files, and context manager basics.

    Ler mais

    Tempo de leitura: 3 minutos
    03/06/2026
    Operações matemáticas usando o módulo math em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python math Module: Mathematical Operations

    Learn Python's math module: sqrt, pow, ceil, floor, trig functions, logarithms, constants like pi and e, and special numeric checks

    Ler mais

    Tempo de leitura: 3 minutos
    03/06/2026
    Uso do módulo time para controlar tempo em scripts Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python time Module for Beginners

    Learn how Python's time module works: Unix timestamp, time.sleep() for pauses, localtime(), strftime() for date formatting, and measure execution time.

    Ler mais

    Tempo de leitura: 3 minutos
    03/06/2026
    Uso da função zip para combinar listas em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python zip() Function: Beginner’s Guide

    Learn how Python zip() works: combine iterables, loop over multiple lists, handle different lengths, unzip with *, and use zip_longest

    Ler mais

    Tempo de leitura: 2 minutos
    03/06/2026
    Uso do módulo collections para estruturas avançadas em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python collections Module: namedtuple to deque

    Learn Python's collections module: namedtuple, Counter, defaultdict, and deque for better performance and readability than built-in lists and dicts.

    Ler mais

    Tempo de leitura: 4 minutos
    03/06/2026