Indentation in Python

What is Indentation in Python?

In Python, indentation refers to the spaces or tabs at the beginning of a line of code. It's a way of showing the structure of the code, indicating which statements belong to which code blocks.


def hello_world():
    print("Hello, world!")

hello_world()

In this example, the print("Hello, world!") statement is indented to show that it's part of the hello_world function. The call to hello_world() is not indented, showing that it's not part of the function's code block.

Python uses indentation as part of its syntax. Other languages use braces {} to show where blocks of code start and end, but Python uses indentation for this. If you get the indentation wrong in Python, you'll get an IndentationError or the program will do something you didn't expect.

The standard practice in Python is to use four spaces for each level of indentation, but tabs or a different number of spaces can also be used. The important thing is to be consistent in the same block of code.

Indentation in Python is not just a matter of style. It's crucial to the program's operation, as Python interpreter uses indentation to determine the grouping of statements or the block of code.

Let us see some more examples below:


def classify_numbers(numbers):
    for number in numbers:
        if number % 2 == 0:
            print(f"{number} is even.")
        else:
            print(f"{number} is odd.")

numbers = [1, 2, 3, 4, 5, 6]
classify_numbers(numbers)

In this example:

The lines of code inside the function classify_numbers are indented one level (four spaces) to the right of the function definition.

The lines inside the for loop are indented one additional level to the right of the for loop.

The print statements inside the if and else conditions are indented one level further.

So, the structure of indentation visually indicates the structure of the code. The code nested inside the function classify_numbers (the for loop and the conditions) is executed each time the function is called. Within the for loop, Python checks each number to see if it's even or odd.

The correct use of indentation allows Python to correctly associate the if/else statements with the for loop, and the for loop with the function. If the indentation were incorrect, it could result in IndentationError, or the code might not behave as expected.

When this program runs, it produces the following output:


1 is odd.
2 is even.
3 is odd.
4 is even.
5 is odd.
6 is even.

Indentationerror Examples

Python's indentation rules might seem straightforward, but it's quite common to encounter errors if you're not careful. Let's look at a few examples.

I. Inconsistent Use of Spaces and Tabs

This is an example of a common indentation error that occurs when you mix spaces and tabs:


def my_function():
    print("Hello")  # this line uses a tab
    print("World")  # this line uses four spaces

Running this code results in a TabError: inconsistent use of tabs and spaces in indentation

To fix this, you should consistently use either tabs or spaces (preferably spaces as per PEP 8 guidelines) within a single block of code.

II. Incorrect Indentation Level

Another common error is when the indentation level is incorrect. For example:


def my_function():
print("Hello, World!")

This will result in an IndentationError: expected an indented block because the print statement inside the function definition is not indented.

The correct indentation:


def my_function():
    print("Hello, World!")

III. Unindent Does Not Match Any Outer Indentation Level

Consider this example:


if True:
    print("Hello, World!")
  print("Goodbye, World!")

Running this code gives IndentationError: unindent does not match any outer indentation level. This is because the second print statement is indented at a level that doesn't match any outer block of code.

The correct indentation:


if True:
    print("Hello, World!")
    print("Goodbye, World!")

Rules for Indentation in Python

  • The first line of python code cannot have an indentation.
  • Each line within the block must be indented by the same amount.
  • There should be consistency in the type and amount of indentation used. Never mix spaces and tabs in the same file.
  • To close a code block, simply return to the previous level of indentation.
  • If you have a multiline statement, align the continuation lines with the opening delimiter (such as a parenthesis or bracket).

Advantages of Indentation in Python

I. Code Readability: Proper indentation makes code easier to read and understand by visually delineating blocks of code. This makes it easier to understand the flow of logic in the program and how different parts of the code interact.

II. Error Reduction: Python's enforcement of indentation helps to reduce errors. With indentation as part of the language syntax, it is much harder to write code with mismatched opening and closing braces, a common error in other languages.

III. Makes Debugging Easier: Since code blocks are clearly separated by their indentation levels, it is easier to identify where an issue might originate and follow the logic to its root cause.

Disadvantages of Indentation in Python

I. Difficulty with Complex Structures: Writing complex nested structures might become challenging due to the strict indentation rules. An increase in indentation levels for nested loops or conditions can sometimes make code less readable.

II. Compatibility Issues: If a code editor or integrated development environment (IDE) doesn't correctly handle tab and space characters, or if it has non-standard settings for these characters, it can lead to issues when running Python code. This can make sharing and collaborating on code more difficult.

III. Challenges in Code Refactoring: If you want to move a block of code around (e.g., moving code inside a loop to outside), you need to be mindful of changing the indentation levels. This might be a bit more work compared to languages where braces {} determine code blocks.

Summary Notes

  • Indentation in Python refers to the spaces or tabs at the beginning of a code line, used to indicate the structure and define code blocks. Unlike other languages that use braces {}, Python relies on indentation.
  • Significance: Indentation isn't just stylistic but syntactical in Python. Errors in indentation lead to IndentationError or unexpected behavior.
  • Standard Practice: Four spaces are recommended for each level of indentation, but tabs can also be used. Consistency within the same block of code is key.
  • Common Errors:
    • Mixing tabs and spaces can lead to TabError.
    • Incorrect indentation levels cause IndentationError.
    • Indenting a line that doesn't match any outer indentation level can also trigger an error
  • Indentation Rules:
    • First code line should not be indented.
    • Lines within the same block must share the same indentation level.
    • Never mix tabs and spaces in the same file.
    • To close a code block, return to the previous level of indentation.
    • Multiline statements should align with the opening delimiter.
  • Advantages:
    • Improved code readability.
    • Error reduction due to enforced indentation.
    • Easier debugging.
  • Disadvantages:
    • Challenges with complex, nested structures.
    • Compatibility issues with different editors.
    • Extra work in code refactoring to adjust indentation levels.

Test Your Knowledge

1. What does indentation in Python refer to?
2. What error is thrown when indentation is incorrect in Python?
3. What is the standard practice for indentation in Python according to PEP 8?
4. What happens if you mix spaces and tabs in Python?
5. Can the first line of Python code have indentation?
6. How does Python interpret differently indented lines?
7. What is the primary advantage of using indentation in Python?
8. What is a disadvantage of strict indentation rules in Python?
Kickstart your IT career with NxtWave
Free Demo