View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Indentation in Python

Updated on 22/01/20257,103 Views

In Python, indentation refers to the use of spaces or tabs at the beginning of a line to define the structure of the code. It’s essential for separating code blocks, making the code readable and ensuring it works correctly.

The problem arises when indentation isn’t done properly, leading to an "IndentationError" in Python.  

Understanding what is indentation in Python with example can help you avoid these errors and improve your code organization. Once you grasp this, you’ll write cleaner, error-free Python code.

In this guide, you’ll learn the importance of indentation, common pitfalls, and how to fix the dreaded indentation error in Python. Read on!

“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”

Essential Indentation Rules for Python

In Python, indentation determines the grouping of statements, a unique feature compared to many other programming languages that use curly braces for this purpose.

The rules for indentation are simple but strict:

  1. Consistent Indentation: Always use the same number of spaces or a tab for each level of indentation. Python does not allow mixing spaces and tabs in the same project.
  2. Block-Level Indentation: Every block of code, such as loops or functions, must be indented to indicate that it is part of the block.
  3. Indentation Error: If your indentation is incorrect, Python will throw an IndentationError, making your code run incorrectly.

Here’s an example to better understand how to apply indentation properly: 

def greet(name):  # Define a function
    if name:  # Check if name is not empty
        print(f"Hello, {name}")  # Indented because it's part of the if block
    else:
        print("Hello, Stranger")  # Indented because it's part of the else block
greet("Ajay")

Output: 

Hello, Ajay

Explanation

  • The function greet checks if a name is passed and prints a greeting.
  • Notice that the if and else blocks are indented with 4 spaces to group the statements inside them.
  • The indentation ensures that Python understands where the function's logic starts and ends.

“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”

How Do Indentation Errors Occur in Python?

Indentation errors in Python typically occur when the program is unable to correctly determine the structure of the code due to inconsistent or incorrect indentation. 

Unlike other languages that use curly braces {} to define blocks of code, Python uses indentation to group statements, which makes it more prone to indentation errors.

Common causes of indentation errors include:

  1. Mixing Tabs and Spaces: Python does not allow you to mix tabs and spaces for indentation. You must choose one method (preferably spaces, as per PEP 8 guidelines) and stick to it throughout your code.
  2. Incorrect Indentation Level: If the indentation level does not match the previous block, Python throws an error. For example, the code inside a function or loop should have an extra indentation level compared to the function/loop declaration.
  3. Missing or Extra Indentation: Forgetting to indent after a control statement (like if-else, for, while, etc.) or adding unnecessary indentation can cause Python to be confused about the structure of your program.

Here’s an example of how an IndentationError in Python can occur: 

def greet(name):  # Define the function
if name:  # Incorrect indentation of the if statement
    print(f"Hello, {name}")  # Indented correctly inside the if block
else:
    print("Hello, Stranger")

Output: 

IndentationError: expected an indented block

Explanation:

  • The error happens because the if statement is not indented correctly. Python expects an indented block after the function definition.
  • To fix this, the if statement should be indented just like the print statement in the example above.

By understanding how and why indentation errors in Python occur, you can prevent these issues and ensure your Python code runs smoothly. 

Fixing Indentation Errors in Python

Fixing indentation errors in Python is straightforward once you understand the cause. 

1. Consistent Use of Spaces or Tabs

The first step in fixing indentation errors is ensuring consistency. Python allows either spaces or tabs for indentation, but you should stick to one throughout your code. The Python PEP 8 style guide recommends using 4 spaces per indentation level.

Example: 

# Correct indentation using spaces
def greet(name):
    if name:
        print(f"Hello, {name}")
    else:
        print("Hello, Stranger")

If you accidentally use a tab in one part and spaces in another, Python will raise an indentation error.

Fix: Ensure you are using either spaces or tabs consistently. In most editors, you can configure it to replace tabs with spaces automatically.

2. Indentation Levels

For nested structures like loops, conditionals, and function definitions, indentation levels need to be consistent. A common mistake is using incorrect indentation for these nested blocks.

Example: 

def greet(name):
    if name:
        print(f"Hello, {name}")
  else:  # This else has incorrect indentation
    print("Hello, Stranger") 

Output: 

IndentationError: unexpected indent

Fix: Ensure that all nested blocks inside functions, loops, and conditionals follow the correct level of indentation: 

def greet(name):
    if name:
        print(f"Hello, {name}")
    else:
        print("Hello, Stranger")

3. Using an IDE or Text Editor with Python Support

Many IDEs and text editors (like PyCharm, VSCode, or Sublime Text) highlight indentation errors and allow you to correct them easily. These editors often include features like:

  • Automatically converting tabs to spaces.
  • Highlighting inconsistent indentation.
  • Showing indentation guides to help you visualize the structure.

By using an appropriate IDE, you can spot and fix indentation errors quickly, making the process smoother.

4. Avoiding Mixed Indentation

One of the most common causes of indentation errors is mixing tabs and spaces. Python is very particular about this, and using a mix will result in an error.

Example: 

def greet(name):
if name:  # Using a tab here
        print(f"Hello, {name}")
    else:  # Using spaces here
        print("Hello, Stranger") 

Output: 

TabError: inconsistent use of tabs and spaces in indentation

Fix: Use either spaces or tabs but not both. The recommended way is to use spaces, and you can configure your editor to convert tabs to spaces automatically.

Once you understand how indentation works in Python, fixing indentation errors becomes much easier. The key is consistency. Always use spaces (preferably 4) and make sure that every nested block is properly aligned with the parent block.

FAQs 

1. What is indentation in Python with example?

A. Indentation in Python with example refers to the spaces or tabs used to define the block of code under a statement like if, for, or a function. Python uses indentation to determine the scope of code blocks, unlike other languages that use curly braces {}.

Example

if True:

    print("This is indented properly")

2. How do indentation errors occur in Python?

A. Indentation error in Python occurs when there is inconsistent or incorrect spacing in the code. This might happen when spaces and tabs are mixed, or when code blocks are not aligned properly. Python requires uniform indentation.

3. What is the difference between spaces and tabs for indentation in Python with example?

A. While both spaces and tabs can be used for indentation in Python, spaces are the preferred method. Mixing spaces and tabs in the same file will lead to indentation error in Python.

4. How can I avoid indentation errors in Python?

A. To avoid indentation errors in Python, use a consistent indentation style. Set your editor to insert spaces (typically 4) instead of tabs. Avoid mixing spaces and tabs within the same code block.

5. How do I fix indentation errors in Python?

A. Fix indentation errors in Python by ensuring all code blocks are aligned properly using spaces or tabs. Most modern text editors show where the indentation errors occur, making it easier to spot and fix them.

6. Why does Python rely on indentation for code structure?

A. Python uses indentation as a key element for defining code blocks. This makes the code more readable and easier to maintain, but it also means indentation error in Python can be a common source of bugs.

7. Can I mix spaces and tabs for indentation in Python with example?

A. No, mixing spaces and tabs for indentation causes indentation errors in Python. It is recommended to use only spaces or only tabs throughout your code.

8. How does the IndentationError in Python appear?

A. The IndentationError in Python appears when the code indentation is inconsistent. For example, Python will raise an error like IndentationError: unexpected indent when you improperly indent a block of code.

9. Can indentation errors be fixed automatically in a text editor?

A. Yes, many text editors and IDEs can automatically correct indentation errors in Python by converting tabs to spaces or aligning blocks of code.

10. Is there a way to view indentation guides in my editor?

A. Yes, most modern IDEs such as PyCharm or VSCode display indentation guides that help you visualize indentation levels, preventing indentation errors in Python.

11. What should I do if I encounter an IndentationError in Python?

A. If you encounter an IndentationError, check your code for inconsistent use of spaces or tabs. Align your code properly and re-run the script.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.