ReviseAlgo Logo

Basic Syntax

Indentation

Python code blocks and structure

Interview: Python-specific syntax

Last Updated: June 12, 2026 5 min read

Python uses indentation (whitespace) to define code blocks instead of curly braces or keywords. This is not optional — it's part of the syntax. Inconsistent indentation causes IndentationError or TabError.

PEP 8 Rules

  • Use 4 spaces per indentation level (never tabs)
  • Never mix tabs and spaces — Python 3 will raise TabError
  • Continuation lines should align with the opening delimiter or use a hanging indent
  • Configure your editor to insert spaces when Tab is pressed

Common Indentation Patterns

  • After : (if, for, def, class, with, try)
  • Multi-line function calls: align arguments or use hanging indent
  • Nested structures: each level adds 4 spaces

Copy-Paste Warning

Copy-pasting code from websites or chat apps often introduces mixed tabs/spaces or inconsistent indentation. Always re-indent pasted code to match your file's style. Tools like ruff format or black can auto-fix this.

Use Cases

Maintaining consistent code style across a team

Avoiding IndentationError and TabError in production code

Writing readable, well-structured Python code

Configuring editor settings for automatic formatting

Common Mistakes

Mixing tabs and spaces (causes TabError in Python 3)

Using tabs instead of 4 spaces

Copy-pasting code with inconsistent indentation

Not configuring the editor to use spaces for tabs