↔️ Indentation

5th Grade 💻 Coding

Indentation means spaces at the beginning of a line. In Python, indentation is part of the language: it shows which lines belong inside a condition, a loop or a function.

Free · US Letter · no sign-up
Google Classroom Save to Pinterest Email me

After a line that ends with a colon (if, else, for, while, def), the lines inside the block start with spaces, usually four. All the lines indented the same amount belong to the same block, and the first line that moves back to the left is already outside it. If the indentation isn’t consistent, Python shows an IndentationError.

In languages like JavaScript, blocks are marked with curly braces, and indentation is only there to make code easier to read. In Python you have no choice, and that’s actually a good thing, because all Python code ends up looking neat. Most code editors add the spaces for you after a colon.

For example

  • In a loop, the print line is indented four spaces under the for line, so Python knows it repeats every time around.
  • Noah accidentally indented one line with three spaces instead of four and got an IndentationError.

📌 Remember: Colon at the end? The next line goes in.

Quick quiz

  1. What is indentation?

  2. In Python, which symbol comes before an indented block?

  3. Which error appears when indentation is inconsistent?

🔎 Ask Thinkapedia another question