Indentation in Python

What is Indentation?

Indentation is the space at the beginning of a line of code.

In other languages, they use {} or end to show where a block of code starts and finishes. Python doesn't. Python uses whitespace. This forces you to write clean code. Whether you like it or not is irrelevant. This is how Python works.

What are Code Blocks?

A code block is a piece of code that is executed as a unit. In other languages, you use curly braces {} to show where a block begins and ends. Python doesn't use those. Python uses whitespace. Specifically, indentation.

This is how Python knows what code belongs to an if statement, a for loop, or a function definition.

Example:

# This line is not indented
weather = 'rain'

# The 'if' statement ends with a colon, so a new code block starts on the next line
if weather == 'rain':
    # This line is indented 4 spaces. It is inside the 'if' block.
    print("Bring an umbrella.")
    
    # This line is also indented 4 spaces. It is also in the 'if' block.
    print("Wear a jacket.")

# This line is not indented. The 'if' block is over.
# This code will run no matter what the weather is.
print("Check the weather again later.")
print("Outside the block.")

The Rules are Simple:

  • Indent to start a block. After a line ending in a colon :, like if, while, or def, the next line must be indented.
  • Keep indentation consistent. All lines in a block must have the same indentation.
  • De-indent to end a block. To end a block, you just go back to the previous level of indentation.

This structure is not a suggestion; the code will not run without it. Getting it wrong causes an IndentationError, one of the most common errors for beginners.

Why Does Python Do This?

It forces you to write clean, readable code. In languages that use braces, you should indent for readability, but you don't have to. This leads to messy code. Python enforces the structure. There's no argument about style; there is only one way.

Tabs vs. Spaces. Just Pick One.

The official style guide (PEP 8) says use 4 spaces per indentation level.

Using a mix of tabs and spaces in the same file will break your code. Python 3 won't allow it.

Solution: Configure your code editor to insert 4 spaces when you press the Tab key. Every decent editor can do this. Problem solved. Don't think about it again.

Common Mistakes:

  • IndentationError: expected an indented block: You wrote a line ending with a colon (:) but didn't indent the next line.
  • IndentationError: unindent does not match any outer indentation level: You have an inconsistent number of spaces. Maybe you used 4 spaces on one line and 2 on the next. Keep it the same.
  • Pasting code: Copy-pasting code from somewhere else can mess up the indentation. Always check it.

Your code editor is your best tool here. It will help you auto-indent and spot errors. Use it.

We will learn in the next lesson:

Scroll to Top