Why indentation is so important in Python


I am aware, this might come as a silly question.
I know indentation is important in Python. Improper indentation will throw bug.

Coming from VBA background, it was strange for me. Though I diligently follow indentation in my VBA code, lack of it does not has any consequences.

In VBA this is a personal choice, for better understanding of the code. Does not have any meaning to it.
Can anyone please explain me why indentation is important in Python, basic rules about indentation.

I believe you answered it yourself:

for better understanding of the code

This I believe is a stylistic choice that Python chose. This is based on some of the principles on which Python was created: https://www.python.org/dev/peps/pep-0020/#id2.

There are those who dislike being forced to do indentation and would prefer it to be optional (I personally like the indentation requirement), but Python does not allow for using braces as tokens to signify opening and closes blocks, so it is integral to the Python syntax.

1 Like

Thanks for the help @facelessuser , have a nice day ahead. :slight_smile:

For more information specifically on the “why” aspect of indentation in Python, I’d recommend consulting the official Design FAQ.

As far as some of the basic rules, in most places you would use normally curly braces {} in other languages, you instead use a colon : followed by 4 spaces [1] of indentation. For example, in C, C++, C#, Java, or most other C-like languages:

if (condition) {
else {

In Python:

if condition:

Similarly in while loops or for loops:

while (1) {
for (int i = 0; i < 10; i++) {
while True:
for i in range(10):

The same applies to subroutine definitions (for functions and methods), class definitions, try-except, and other types of statements (such as Python’s with statement). For more examples, see https://docs.python.org/3/reference/compound_stmts.html.

Note that the indentation is technically optional for statements that only have a scope of one line, I.E. if conditional: do_something(), is valid code. You can also use scopes with multiple parts on a single line with a semicolon using if conditional: do_something(); do_another_thing(), but this is discouraged outside of a few specific use cases [2]. 90% of the time, it’s preferable to use indentation for the sake of readability.

[1] - 4 is technically not the only syntactically valid number of spaces, and tabs can also be used (as long as they aren’t mixed). For more technical details, see https://docs.python.org/3/reference/lexical_analysis.html#indentation.

[2] - A couple specific use cases of the semicolon to combine multiple parts into a single line being useful is when executing a few lines of code with `python -c “do_something(); do_another_thing()” and for benchmarking a few lines of code with timeit. I’d recommend against it for most normal code though.

1 Like

Hi @aeros , thanks a lot for the help. Have a nice day ahead. :slight_smile: