Mastering Indentation in Python: A Beginner’s Guide

Mastering Indentation in Python

In Python, indentation is a fundamental part of its syntax. Python is heavily dependent on indentation to structure its programs. Even if there’s a slight error in the indentation of the code, the entire code will throw an error. This means that how we align our code directly affects how it runs.

Even a small indentation mistake can break your entire program. Many of these are also covered in our article on common Python errors students make.

Proper indentation ensures readability, prevents errors, and maintains a logical flow, making writing and understanding code easier. In this article, we will explore the significance of indentation, its rules, common mistakes, and best practices to follow.

Summary of the article (This article will cover:)
1. What indentation is in Python – understanding how whitespace determines the structure of Python programs.
2. Why indentation is important – how it affects readability and prevents syntax errors.
3. Basic rules and best practices – following standard conventions to maintain clean and consistent code.
4. Common mistakes and how to avoid them – identifying and fixing indentation-related errors.
By the time you finish reading this article, you will know without a doubt the concept of Python indentation and proper usage in code.

What is Python Indentation? Read Below

Indentation in Python refers to the spaces or tabs added at the beginning of a line. It is used to determine the structure of the program. It groups statements together, allowing Python to recognize which lines of code belong to the same block.
In most other languages, code blocks are enclosed in curly braces {} or marked with specific keywords. In C, for instance, or Java, or JavaScript, an if statement looks like this:

				
					if (condition) {
    // Code block
    System.out.println("Condition is True");
}

				
			

Python doesn’t have any braces. Python uses indentation instead to indicate code blocks:

				
					if condition:
    # Code block
    print("Condition is True")

				
			

The indentation here indicates to Python that the print() statement is part of the if block. If we do not indent it correctly, Python will throw an error:

				
					if condition:
print("Condition is True") # This will result in an IndentationError

				
			

Since indentation is a basic requirement in Python, we always have to be cautious while writing our code. Even a tiny discrepancy such as using a tab and not spaces or vice versa can lead to bugs.

What is the Importance of Indentation?

In Python, indentation is not merely done for the sake of making the code look clean—it’s actually a fundamental component of the language. Unlike most other programming languages that utilize curly braces {} or keywords to delimit and define code blocks, Python does not use these at all. Instead, it uses indentation exclusively.

This is what makes Python so readable and also ensures that every program has a uniform structure. 

But this comes with a catch: bad indentation will result in syntax errors or unwanted logic in our programs.
Correct indentation makes sure that the program runs as it should and is still easy to read. 

If that’s not the case, Python will throw an IndentationError, immediately stopping the execution of our program. This particular feature of Python distinguishes it from other languages, which highlights the significance of coding with clean, well-structured, and correctly indented code.

Here’s an example of incorrect indentation that leads to an error:

				
					def greet():
print("Hello, world!")  # This line is not indented correctly

				
			

Output: 

incorrect indentation that leads to an error Output

Even when there is no syntax error, improper indentation can cause logical errors where the program runs but does not behave as expected. For example:

				
					x = 5


if x > 3:
    print("X is greater than 3")  
    print("This is inside the if statement")  


print("This is outside the if statement")  # This line is not indented

				
			

If we mistakenly indent the last print() statement, Python will assume it is still part of the if block which could change the program’s behaviour.

Because indentation directly affects how Python reads and executes code, we must always be mindful of how we structure our programs. Now, let’s go over some basic rules to ensure our indentation is correct.

What Are Some Basic Rules of Indentation? Read Below

To maintain clean and error-free Python code, we should follow some essential indentation rules:

  • Use Four Spaces Per Indentation Level

Python’s official style guide, PEP 8, recommends using four spaces for each indentation level. This ensures consistency and improves code readability.

				
					def greet():
    print("Hello, world!")  # Indented with four spaces

				
			

While Python allows the use of tabs, the standard practice is to use spaces since they are more universally supported across different text editors and IDEs.

  •  Do Not Mix Tabs and Spaces

Mixing tabs and spaces in the same code can cause unexpected errors. Python strictly enforces indentation consistency, so using both can lead to a TabError.

				
					def greet():
    print("Hello, world!")  # Using spaces
	print("Goodbye!")  # Using a tab (This will cause an error)

				
			

To avoid this, we can configure our text editor or IDE to automatically insert spaces when pressing the Tab key.

  • Maintain Consistency Throughout the Code

Consistency is key when working with indentation. If we choose to use four spaces (which is recommended), we must stick to it throughout the entire codebase. Mixing different indentation levels in different parts of the program makes the code harder to read and can cause errors.

By following these basic rules, we can write well-structured Python code that is easy to read, understand, and execute correctly. In the next section, we will see how indentation is used in different control structures like loops, functions, and conditionals.

Process of Indentation in Control Structures

Indentation is very important when writing control structures like conditional statements, loops, functions, and classes, and because Python does not use braces} to define blocks of code, indentation is what tells the interpreter which lines belong to which particular block. Let’s explore how indentation is applied in different control structures.

Understanding how indentation affects loops and functions is critical, especially when working with data structures in Python, where loops and nesting are frequently used.

  • Conditional Statements (if, elif, else)

Each block of code under an if, elif, or else statement must be indented properly.

Example:

				
					age = 18


if age >= 18:
    print("You are eligible to vote.")
    print("Make sure to carry an ID.")
else:
    print("You are not eligible to vote yet.")

				
			

Output: 

Indentation in Control Structures

Here, both print statements inside the if block are indented, meaning they will execute only if the condition age >= 18 is True. Similarly, the statement inside the else block runs if the condition is False.

For nested conditions, indentation should be used consistently:

				
					score = 85


if score >= 50:
    print("You passed the test.")
    
    if score >= 80:
        print("You scored an A grade!")
    else:
        print("You can do better next time.")
else:
    print("You failed the test. Try again.")

				
			

Output: 

nested conditions Output

Here, the second if statement is indented further inside the first if block, which makes it a nested condition.

  • Loops (for, while)

Loops also require indentation to define which lines should be executed repeatedly. Let’s see an example with a for loop:

				
					numbers = [1, 2, 3, 4, 5]


for num in numbers:
    print("Number:", num)  # This line is inside the loop
print("Loop finished")  # This line is outside the loop

				
			

Output: 

Loops (for, while) Output

Since the print(“Number:”, num) statement is indented, it executes inside the loop, printing each number in the list. The print(“Loop finished”) statement is not indented, so it runs after the loop ends.

Example of a nested loop:

				
					for i in range(1, 4):
    for j in range(1, 4):
        print(f"i={i}, j={j}")
    print("Inner loop finished")

				
			

Output: 

nested loop Output

Each iteration of the outer loop (i) executes the entire inner loop (j). The indentation helps us see that print(f”i={i}, j={j}”) belongs to the inner loop, while print(“Inner loop finished”) runs after the inner loop completes.

  • Function and Class Definitions

When defining functions and classes, proper indentation is necessary to specify which statements belong inside the function or class body.

Example of a function with indentation:

				
					def greet(name):
    print("Hello,", name)
    print("Welcome to Python!")


greet("Taffy")

				
			

Output: 

function with indentation Output

The statements inside the greet function are indented, meaning they only execute when the function is called.

Example of a class with indentation:

				
					class Animal:
    def __init__(self, name):
        self.name = name


    def speak(self):
        print(self.name, "makes a sound.")


dog = Animal("Dog")
dog.speak()

				
			

Output: 

class with indentation

The __init__ and speak methods are properly indented inside the Animal class. Any method inside a class must be indented to indicate that it belongs to that class.

What Are Some Common Indentation Errors?

Mistakes in indentation can lead to errors or unexpected program behaviour. Let’s look at some common indentation errors.

  • IndentationError

This occurs when Python encounters unexpected indentation.

Example of an IndentationError:

				
					x = 5


    print(x)  # This line has unnecessary indentation

				
			

Python will raise:

IndentationError Output

  • Logical Errors Due to Wrong Indentation

Sometimes, incorrect indentation may not cause a syntax error, but it can change the program’s behavior in an unintended way.

Example:

				
					marks = 80


if marks >= 50:
    print("You passed!")


print("Congratulations!")  # This line is not indented correctly
else:
    print("Try again.")  

				
			

This will raise a SyntaxError because both the print statements must be at the same indentation level inside if.

By understanding and following correct indentation practices, we can avoid these errors and write clean, readable, and error-free Python code.

What Are Some Best Practices for Indentation?

To keep our Python code clean and readable, we need to follow some best practices for indentation. Even a small mistake can cause errors or make the code harder to understand. Here are some simple but important rules to follow:

  • Always Use Four Spaces Per Indentation Level

Python’s official style guide, PEP 8, recommends using four spaces for each level of indentation. This makes the code uniform and easy to read.

Good Practice: Using Four Spaces

				
					def greet(name):
    print("Hello,", name)
    print("Welcome!")

				
			

 Bad Practice: Using Two Spaces:

				
					def greet(name):
  print("Hello,", name)  # Only two spaces, not recommended
  print("Welcome!")

				
			

Bad Practice:Using a tab

				
					def greet(name):
	print("Hello,", name)  # Uses a tab instead of spaces
	print("Welcome!")


				
			

Using tabs instead of spaces (or mixing both) can cause errors in some environments, so it’s best to stick to four spaces.

  • Configure Your Editor to Use Spaces Instead of Tabs

Most modern code editors and IDEs let us configure indentation settings. We should enable the option to insert spaces when pressing the Tab key to avoid accidentally using tabs.

  • In VS Code:
    1. Open Settings (Ctrl + ,)
    2. Search for “Insert Spaces” and enable it
    3. Set “Tab Size” to 4
  • In PyCharm:
    1. Go to File → Settings → Editor → Code Style → Python
    2. Set “Tab size” and “Indent” to 4
    3. Check the box “Use tab character” (if unchecked, spaces will be used)

These settings ensure our code is always indented correctly, without worrying about mixing spaces and tabs.

Python Version Differences in Indentation

Python has evolved over the years, and indentation has always been a core part of the language. There have been some version-specific changes that we should be aware of.

  • Stricter Indentation Rules:
    Older versions of Python (like Python 2) were slightly more lenient when it came to mixing spaces and tabs, whereas Python 3 strictly focuses on consistent indentation. This means that code that worked in Python 2 might throw indentation errors in Python 3.
  • Changes in Indentation Error Handling:
    Newer versions of Python provide clearer and more specific error messages for indentation issues. This helps us to debug faster compared to older versions, where indentation errors were sometimes harder to interpret.

What Are Real-World Implications of Improper Indentation?

Indentation in Python isn’t just about keeping the code neat, it directly affects how the program runs. A small indentation mistake can lead to unexpected behavior, software bugs, or even security vulnerabilities. Here’s how improper indentation can cause problems in real-world scenarios:

For example, in 2014, a major security flaw in Apple’s SSL/TLS implementation (commonly known as the “goto fail” bug) was caused by improper indentation. This bug made encrypted connections vulnerable to attacks, which allowed hackers to intercept sensitive data.

A missing indentation level can cause a crucial if condition to be ignored, which demonstrates how a tiny mistake in Python’s whitespace sensitivity can lead to catastrophic failures.

Security Risks Due to Indentation Errors

In security-sensitive applications, incorrect indentation can introduce vulnerabilities. Imagine an authentication system where a small indentation mistake could allow unauthorized access:

 Incorrect Indentation (Security Flaw)

				
					def authenticate(user, password):
    if user == "admin" and password == "secure123":
        print("Access granted.")
        print("Access denied.")  # Always runs due to incorrect indentation

				
			

Here, even valid users would see “Access denied” due to the indentation mistake.

Correct Code (Secure Authentication Check):

				
					def authenticate(user, password):
    if user == "admin" and password == "secure123":
        print("Access granted.")
    else:
        print("Access denied.")

				
			

Code Reviews Help Catch Indentation Mistakes

To prevent such issues, code reviews are essential. Having another developer review the code can catch indentation errors before they cause real problems. Some best practices for catching indentation issues include:

  • Using version control (Git) to track indentation changes
  • Running linters like flake8 to spot errors early
  • Reviewing indentation manually before deploying critical code

Conclusion:

Indentation in Python isn’t just about style but is more fundamental to how the language works. A single indentation mistake can break the program, cause unexpected behaviour, or introduce security risks.

Clean indentation not only prevents bugs but also helps during code reviews, debugging, and writing assignments or projects in Python more efficiently.

Key Takeaways:

  • Always use four spaces per indentation level (as per PEP 8).
  • Avoid mixing tabs and spaces to prevent compatibility issues.
  • Use IDEs and linters to catch indentation problems early.
  • Conduct regular code reviews to identify and fix indentation errors.

I hope by now you have mastered indentation in Python and can write and present your code in a clean and structured manner.