Back to course

Understanding Python Indentation (The Python Way)

Python Programming: The 0 to Hero Bootcamp

Indentation: Python's Structure

In many programming languages, blocks of code (like the body of a loop or an if statement) are defined by curly braces ({}). Python uses whitespace indentation for this purpose.

This is critical: Indentation is not optional; it is syntactically required.

The Rule

  • A block of code starts after a colon (:).
  • All statements belonging to that block must be indented at the same level.
  • Standard Python convention (PEP 8) is to use 4 spaces for indentation.

Example of Correct Indentation

python score = 90

if score > 80: # Start of the block # 4 spaces indentation here print("Great job!") print("You passed the test.")

This line is not part of the 'if' block

print("Program finished.")

Indentation Errors

If you mix tabs and spaces, or if your indentation levels are inconsistent within the same block, Python will raise an IndentationError.

python

This would cause an error:

if score > 80:

print("Oops") # 3 spaces

print("Error") # 4 spaces

Always configure your code editor (like VS Code or PyCharm) to automatically convert tabs to 4 spaces.