CodeBlanks Logo Icon CodeBlanks

Indentation blocks

Learn Python's indentation-based block structure.

What is indentation?

In Python indentation shows which block a line of code belongs to. While other languages use curly braces { }, Python uses whitespace.

Lines after an if or for line are inside that block when they are indented. The standard indent is four spaces.

if True:
    print("Yes")
    print("Still inside the block")

If indentation is inconsistent Python raises an IndentationError. So follow the indent size your team uses.

Inconsistent indent error

Lines in the same block must be indented the same amount. If one line has a different number of spaces, Python raises an error.

if True:
    print("A")
      print("B")  # 6 spaces — error

Do not mix tabs and spaces. Make your editor convert tabs to spaces. PEP 8 recommends four spaces.

Practice Write the if block

Write a block starting with if True:. Inside the block, print Indent works with print. Indent with four spaces.

Starter code

main.py
if True:

Sample solution

main.py
if True:
    print("Indent works")

Expected output

Indent works

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What defines blocks in Python?

  • Curly braces
  • Parentheses
  • Semicolons
  • Indentation Correct answer

Explanation: Python uses indentation to define blocks.

2 Complete the block

Question
if True:
    ____("Yes")
Answer
if True:
    print("Yes")

Explanation: print is inside the if block.

3 Match each concept

Term Meaning
Indent Block definition
Four spaces PEP 8 standard
Tab Do not mix with spaces
IndentationError Inconsistent indent

All lessons in Beginner