Skip to content

IndentationError: expected indented 块

错误信息

                expected indented 块
              

快速摘要

Python uses indentation 到定义 code 块 — 错误, missing, or inconsistent indentation breaks 结构.

为什么发生

  • Missing indentation 之后 colon (如果, for, def, etc.)

  • Mixed tabs and 空间 in 相同 file

  • Inconsistent indentation level 在内相同块

最小示例

✗ 错误代码
if x == 5:
print("yes")
✓ 修复代码
if x == 5:
    print("yes")

Python expects indented 块之后 如果: 行 — indent print 通过 4 空间所以它's 部分的 如果 块.

如何诊断

  • 检查行 之后 colon — 是它 indented?

  • 运行 python -t 到 warn 关于 mixed tabs and 空间

  • Look for 可见 whitespace characters in 你的 editor

如何修复

  • Indent 行之后 colon 使用 4 空间

  • Convert 所有 tabs 到空间 (大多数 editors 有这个 option)

  • Ensure consistent indentation 在内每个块

如何预防

  • 配置你的 editor 到 use 4 空间 for Python (PEP 8)

  • Use formatter 如 black 到 normalize indentation automatically

相关资源

相关术语

相关课程

相关练习

← 返回语言