Indentation
一句话解释
Indentation 是 leading whitespace 之前 行 的 code. In Python, 它 定义 code 块 相反 的 braces.
用大白话说
In Python, indentation is not just for readability — it is syntactically significant. The number of spaces at the start of a line determines which block of code the line belongs to. This is how Python groups statements, instead of using curly braces like JavaScript or C.
Consistent indentation is mandatory. Mixing tabs and spaces causes errors. The convention is four spaces per level (PEP 8). A line inside an 如果, for, or def must be indented one level deeper than the statement that introduces the block.
Indentation makes Python code visually clean and forces a consistent style. The downside is that a single misplaced space can change the meaning of your code or cause an IndentationError. Most editors handle this automatically, but it is important to understand.
示例
age = 20
if age >= 18:
print("Adult") # indented — inside the if
print("Can vote") # indented — inside the if
print("Done") # not indented — outside the if
# Wrong indentation causes an error:
# if age >= 18:
# print("Adult") # IndentationError: expected an indented block行 indented under 如果 belong 到 如果-块. unindented 行 运行 regardless. 错误 indentation 是 语法 错误.
常见混淆
容易混淆的对象: braces
关键区别: Python uses indentation 到 定义 code 块; 大多数 other languages (JavaScript, Java, C) use curly braces {}. Indentation 是 mandatory and 语义 in Python, 虽然 braces 是 mandatory and indentation 是 可选 (样式 仅) in 那些 languages.
相关术语
相关资源
相关课程
- 条件 and 循环
Indentation 定义 块 in 条件 and 循环
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。