Skip to content

1.3 Indentation

Indentation is a crucial aspect of Python programming that defines the structure and flow of your code. Unlike many other programming languages that use braces {} to define blocks of code, Python relies on indentation (whitespace) to denote code blocks.

1.3a What is indentation?

Indentation refers to the spaces or tabs at the beginning of a line of code. In Python, indentation is used to group statements together to form a block of code.

 


 

1.3b Why is indentation important in Python?

  • Defines Code Blocks - In Python, the level of indentation determines which statements are part of the same block. This is essential for control structures such as loops, conditionals, and function definitions.

  • Enhances Readability - Indentation improves the readability of the code by visually separating different blocks of code, making it easier to understand the structure and flow of the program.

 


 

1.3c Rules for indentation in Python

  • Consistent Indentation- All lines of code in a block must have the same level of indentation. Mixing spaces and tabs is discouraged and can lead to errors.

  • Indentation Levels - A standard practice is to use 4 spaces per indentation level, although other conventions (such as 2 spaces) are also acceptable as long as you are consistent.

  • Indentation Errors - Incorrect indentation will result in an IndentationError. For example, if the indentation is inconsistent within a block, Python will raise an error.

 


 

1.3d Common indentation errors

Example 1.3.1 - Inconsistent indentation

if x > 5:
  print("x is greater than 5")  # Using 2 spaces
    print("This will cause an error")  # Using 4 spaces

 

Example 1.3.2 - Missing indentation

for i in range(3):
print(i)  # This line is not indented

 

Example 1.3.3 - Mixing tabs and spaces

if x > 5:
    print("x is greater than 5")  # Using spaces
    print("This will cause an error")  # Using a tab

 


 

1.3e Best practices

  • Use Spaces, Not Tabs - It is recommended to use spaces instead of tabs for indentation. Most Python style guides, including PEP 8, recommend using 4 spaces per indentation level.

  • Consistent Indentation - Be consistent with your indentation throughout your code to avoid errors and improve readability.

  • Code Editors - Use a code editor or IDE that supports Python and automatically handles indentation for you, such as Thonny IDE, Visual Studio Code, PyCharm, or even IDLE.

 


 

Note

Indentation in Python is not just a matter of style but a fundamental part of the language's syntax. Proper indentation is essential for defining the structure and flow of your code. By adhering to consistent indentation practices, you ensure that your code is both functional and readable.