Indentation

Python uses indentation, not braces, to group code into blocks.

Syntaxif condition: do_something()

Most languages group code with curly braces. Python uses indentation — the spaces at the start of a line — instead. This forces clean, readable code.

The rules

  • A block starts after a line ending in a colon :.
  • Every line in the same block must be indented by the same amount.
  • The standard is 4 spaces per level.

Getting indentation wrong is one of the most common beginner errors, so be consistent.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A developer structures an if/else block so only the correct branch runs based on user input.
  • A Python linter flags mixed tabs and spaces, causing an IndentationError that breaks the build.
  • A nested loop processes rows and columns of a spreadsheet using two levels of indentation.

More examples

If block with indentation

Shows that the two indented lines are inside the if block; the last line always runs.

Example · python
temperature = 30
if temperature > 25:
    print('It is warm')
    print('Wear light clothes')
print('Have a good day')

# Output:
# It is warm
# Wear light clothes
# Have a good day

Nested indentation levels

Demonstrates two levels of indentation for nested loops, each adding 4 spaces.

Example · python
for row in [1, 2]:
    for col in ['A', 'B']:
        cell = f'{col}{row}'
        print(cell)

# Output:
# A1
# B1
# A2
# B2

IndentationError example

Illustrates that missing indentation after a colon causes an IndentationError.

Example · python
# This code has a wrong indentation and will raise IndentationError:
# if True:
# print('oops')  # no indent — error!

# Correct version:
if True:
    print('correct')

# Output:
# correct

Discussion

  • Be the first to comment on this lesson.