Skip to content

IndentationError: expected an indented block

Error message

                expected an indented block
              

Quick summary

Python uses indentation to define code blocks — wrong, missing, or inconsistent indentation breaks the structure.

Why this happens

  • Missing indentation after a colon (if, for, def, etc.)

  • Mixed tabs and spaces in the same file

  • Inconsistent indentation level within the same block

Minimal example

✗ Broken code
if x == 5:
print("yes")
✓ Fixed code
if x == 5:
    print("yes")

Python expects an indented block after the if: line — indent print by 4 spaces so it's part of the if block.

How to diagnose

  • Check the line after a colon — is it indented?

  • Run python -t to warn about mixed tabs and spaces

  • Look for visible whitespace characters in your editor

How to fix

  • Indent the line after a colon with 4 spaces

  • Convert all tabs to spaces (most editors have this option)

  • Ensure consistent indentation within each block

How to prevent

  • Configure your editor to use 4 spaces for Python (PEP 8)

  • Use a formatter like black to normalize indentation automatically

Related Resources

Related Glossary

Related Lessons

Related Practice

← Back to language