How Does Indentation Work in Python Control Structures?

In Python, indentation is used for grouping statements within control structures (such as if/else statements, loops, functions, and classes) to indicate a distinct block of code.

Indentation refers to the amount of spaces or tabs at the beginning of a line of code, which must be used consistently within the code block. Otherwise, this can lead to syntax errors.

Consider for example, the if/else statement:

x = 10
if x > 5:
    print('x is greater than 5')
else:
    print('x is less than or equal to 5')

In this example, the two print statements are indented with four spaces. The important thing to note is that, the if and else statements are at the same indentation level, and the statements inside the if and else blocks have the same indentation level.

Similarly, for loops, the statements within the loop must have the same indentation level. For example:

for i in range(10):
    print(i)
    print('foo')

In this example, both the print statements have the same indentation level, and are therefore part of the loop's block.

In Python, the amount of indentation you add doesn't really matter, as long as it is consistent throughout the block of code. However, the recommended convention for indentation is to use four spaces per level of indentation.

Indentation errors are common in Python, and can result in syntax errors. If the indentation is not consistent, the Python interpreter will raise an IndentationError:

if True:
// IndentationError: expected an indented block
print('foo')

It's important to be careful with indentation in Python code to avoid these types of errors. To fix this error, you can simply add an indentation of one or more spaces before the print statement:

if True:
    print('foo')

Now the print statement is correctly indented with four spaces, so the code will execute without any errors.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.