Indentation In Python

One of the most unique and important features of the Python programming language is its indentation system. While other programming languages, such as C, C++, Java, and JavaScript, use curly brackets { } to indicate where a block of code (such as a loop, function, or conditional statement) begins and ends, Python handles this task entirely with whitespace.

Simply put, indentation refers to the spaces or tabs placed at the beginning of a line of code. In Python, this isn't just for the sake of making the code look pretty, but it's an essential part of the syntax.

How does indentation work ?

Whenever you start a block of code in Python (such as an if statement, a for loop, or a def function), a colon (:) is placed at the end of that statement. All lines immediately following this colon must begin with a space. This space tells the interpreter that these lines are all part of the same block.

if 5 > 2:
    print("5 is actually greater than 2!") # Indentation of 4 spaces
    print("This line is also inside an 'if' block.")

print("This line is outside the 'if' block because its indentation is broken.")

Strict Rules of Indentation

If you are writing code in Python, you must strictly follow these rules :
1. Uniformity Rule : All lines within the same code block must have exactly the same number of spaces. If you give 4 spaces in the first line and 5 spaces in the second, the code will not run.
2. Standard Spaces : As a rule, you can use any number of spaces from 1, but according to Python's official style guide (PEP 8), 4 spaces are considered the most ideal and standard.
3. Tabs vs Spaces : You should use either only 'Tabs' or only 'Spaces' throughout your program. Mixing the two creates confusion in the code and leads to errors.

Some Indentation Errors

A. IndentationError: expected an indented block : This error occurs when you start a block (by using a colon :), but forget to give a space on the next line.

if True:
print("Hello")
Code Output
IndentationError: expected an indented block after 'if' statement on line 1

B. IndentationError: unindent does not match any outer indentation level : This error occurs when you give different amount of spaces inside the same block.

def my_function():
    print("First Line")   print("first line") # 4 spaces
     print("Second Line")   #5 Space (Mistake: Space mismatched!)
Code Output
IndentationError: unindent does not match any outer indentation level

Advantages Of Python Indentation

1. Unmatched Readability : Since every developer has to provide spaces, all Python code always looks neat and organized.
2. Freedom from curly brackets : The absence of { } and semi-colon ; in the code makes the code look much lighter, modern and less clutter-free.
3. Fewer Logical Bugs : In other languages, developers often forget to use the closing bracket }, which makes it difficult to find logical errors. In Python, the block ends automatically as soon as the indentation ends.