Skip to content

Blocks

In Python, code blocks are indented. This indentation must be consistent, i.e. all lines of a block must be indented by the same amount. Although tabs are also permitted as characters in principle, spaces are common. A block begins with a colon : and ends when the indentation is cancelled:

if True:
    print("This is the first line of the block.")
    print("This is the second line of the block.")

This is important because, for example, it is necessary to express which parts of a code are relevant for loops and conditions. An example:

value = 42
if value > 10:
    print ("The number is greater than 10.") # the first block
if value > 20:
    print ("The number is greater than 20.") # the second block
print ("Done.")

Two blocks are defined here (see comments). This means that the first two print statements are always executed if the conditions above them are fulfilled. The last print instruction is always executed. If the second block is also indented, the behaviour changes:

value = 42
if value > 10:
    print ("The number is greater than 10.") # the first block starts here
    if value > 20:
        print ("The number is greater than 20.") # the second block consists of this one line
    # the first block ends here
print ("Done.")

Here, the two blocks are nested: the second block is only executed if the condition of the first block is fulfilled. The last print instruction is always executed. A nested structure always requires that an indented block is always completely contained in the parent block. This is the case here.

Formally, nested conditions and linked conditions are equivalent:

value = 42
if value % 3 == 0:
    if value % 7 == 0:
        print("The number is divisible by 3 and 7.")

is equivalent to

value = 42
if value % 3 == 0 and value % 7 == 0:
    print("The number is divisible by 3 and 7.")