Best Practices

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.

Indentation

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.

  • Example 1: correct indentation in an if block
x = 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.

  • Example 2: incorrect indentation in an if block
x = 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

  • Example 3: indentation error in nesting
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.