Objectives
In Python as in programming in general, it is important to understand and respect syntactic conventions, at the risk of getting errors or unexpected behavior from the program. In this page, you will find all the best practices to implement as early as possible when writing Python programs.
In Python, indentation is crucial. Each code block that follows an if, elif, else, while, for, def, must be indented consistently.
Indeed, it is indentation that determines whether an instruction belongs to the current block or not. You can create indentation using the Tab key.
if blockx = 10
# Correct indentation
if x > 5:
print("x is greater than 5")
print("This message is part of the 'if' block")
print("This message is outside the 'if' block")
Explanation
The first two print instructions are indented, so they are part of the if block.
The last print instruction is not indented, it executes independently of the if.
if blockx = 10
# Incorrect indentation
if x > 5:
print("x is greater than 5")
print("This message is part of the 'if' block") # Bad indentation
Explanation
The second print instruction is not indented, so it is not part of the if block. It will therefore be executed, regardless of the value of x > 5
x = 10
y = 5
if x > 5:
print("x is greater than 5")
if y > 3:
print("y is greater than 3") # Bad indentation
Explanations
The second print instruction is not indented, so it is not part of the if y > 3 block.
Python will return an error, because at least one indented instruction is required after if, elif, else, while, for, def instructions.