Python Syntax and Semantics - Indentation

Indentation

Python uses whitespace to delimit program blocks, following the off-side rule. Its uncommon block marking convention is a feature that many programmers, otherwise unfamiliar with Python, have heard of. Python borrows this feature from its predecessor ABC — instead of punctuation or keywords, it uses indentation to indicate the run of a block.

In so-called "free-format" languages, that use the block structure derived from ALGOL, blocks of code are set off with braces ({ }) or keywords. In most coding conventions for these languages, programmers conventionally indent the code within a block, to visually set it apart from the surrounding code (prettyprinting).

Consider a function, foo, which is passed a single parameter, x, and if the parameter is 0 will call bar and baz, otherwise it will call qux, passing x, and also call itself recursively, passing x-1 as the parameter. Here are implementations of this function in both C and Python:

foo function in C with K&R indent style:

void foo(int x) { if (x == 0) { bar; baz; } else { qux(x); foo(x - 1); } }

foo function in Python:

def foo(x): if not x: bar baz else: qux(x) foo(x - 1)

Python mandates a convention that programmers in ALGOL-style languages often follow. Moreover, in free-form syntax, since indentation is ignored, good indentation cannot be enforced by an interpreter or compiler. Incorrectly indented code can be understood by human reader differently than does a compiler or interpreter. For example:

Misleading indentation in C:

for (i = 0; i < 20; ++i) a; b; c;

This code was intended to call functions a and b 20 times. However, the iterated code block is just {a;}. The code calls a 20 times, and then calls b and c only one time each. Later readers of the code may be fooled by the misalignment of the calls to functions b and c.

Both space characters and tab characters are currently accepted as forms of indentation in Python. Since many tools do not visually distinguish them, mixing spaces and tabs can create bugs that take specific efforts to find (a perennial suggestion among Python users has been removing tabs as block markers — except, of course, among those Python users who propound removing spaces instead). Moreover, formatting routines which remove whitespace — for instance, many Internet forums — can destroy the syntax of a Python program, whereas a program in a bracketed language would merely become more difficult to read.

Many popular code editors handle Python's indentation conventions seamlessly, sometimes after a configuration option is enabled.

Read more about this topic:  Python Syntax And Semantics