1. Why Python Uses Indentation to Define Code Blocks
Most programming languages use special symbols to mark code blocks.
For example, Java uses curly braces:
if (age >= 18) {
System.out.println("成年人");
}
JavaScript also uses curly braces:
if (age >= 18) {
console.log("成年人");
}
Python, however, uses indentation to represent code blocks:
if age >= 18:
print("成年人")
Python uses indentation to clearly express the hierarchical relationships between lines of code.
This design has several characteristics:
- Clear structure: The hierarchy of code blocks is reflected through visual indentation.
- Fewer symbols: There is no need to use large numbers of curly braces.
- Consistent style: All developers need to follow the same basic indentation rules.
- Emphasis on readability: Code structure and visual structure remain consistent.
It is important to note that indentation in Python is not merely a formatting habit; it is part of the syntax. Indentation errors can directly prevent a program from running or change the scope of code execution.
2. Basic Python Indentation Rules
Python's indentation rules mainly include the following:
- Statements in the same code block must maintain the same indentation level.
- A new code block usually adds one level of indentation.
- By default, 4 spaces per level are recommended.
- Do not mix tabs and spaces.
- When a code block ends, it is exited by returning to the previous indentation level.
2.1 Use 4 Spaces for Indentation
PEP 8 recommends using 4 spaces for each indentation level.
if True:
print("第一层缩进")
if True:
print("第二层缩进")
if True:
print("第三层缩进")
The corresponding hierarchy is as follows:
| Code Level | Number of Indentation Spaces | Description |
|---|---|---|
| Level 1 | 0 | Top-level code |
| Level 2 | 4 | First code block |
| Level 3 | 8 | Second level of nesting |
| Level 4 | 12 | Third level of nesting |
| Level 5 | 16 | Fourth level of nesting |
Indentation levels should remain stable; do not arbitrarily change the number of spaces within the same code block.
2.2 The Same Code Block Must Be Consistent
Correct example:
if age >= 18:
print("成年人")
print("可以申请相关服务")
print("完成年龄检查")
Incorrect example:
if age >= 18:
print("成年人")
print("可以申请相关服务")
The second print() is indented one level more than the other statements in the same code block, but no new code block was opened before it, so this produces an indentation error.
2.3 Restore Indentation When a Code Block Ends
Python determines the scope of a code block by indentation level.
if age >= 18:
print("成年人")
print("允许访问")
print("程序继续执行")
The last print() returns to the top level, indicating that it is no longer part of the if code block.
3. How Python Code Blocks Are Formed
In Python, a code block is usually introduced by a colon :.
The colon indicates that a new compound statement code block will follow.
Common code block entries include:
| Syntax structure | Example | Purpose |
|---|---|---|
| if | if condition: |
Conditional branch |
| elif | elif condition: |
Additional conditional branch |
| else | else: |
Default branch |
| for | for item in items: |
Iteration loop |
| while | while condition: |
Conditional loop |
| def | def func(): |
Function definition |
| class | class User: |
Class definition |
| try | try: |
Exception handling |
| except | except Exception: |
Exception catching |
| finally | finally: |
Exception handling cleanup |
| with | with open(...) as f: |
Context management |
| match | match value: |
Pattern matching |
| case | case pattern: |
Pattern matching branch |
3.1 if Conditional Code Block
age = 20
if age >= 18:
print("成年人")
print("允许进入")
print("年龄检查结束")
Execution flow:
flowchart TD
A["Start"] --> B["Check age >= 18"]
B --> C{"Condition true?"}
C -->|Yes| D["Execute the if block"]
C -->|No| E["Skip the if block"]
D --> F["Execute subsequent code"]
E --> F
F --> G["End"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
3.2 if, elif, else Multi-branch Structure
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 60:
print("及格")
else:
print("不及格")
Each branch has its own code block, but they are part of the same conditional structure.
Note that elif and else maintain the same indentation as the corresponding if, while the statements inside them are indented one level further.
flowchart TD
A["Start"] --> B["Check if score >= 90"]
B --> C{"Met?"}
C -->|Yes| D["Output Excellent"]
C -->|No| E["Check if score >= 80"]
E --> F{"Met?"}
F -->|Yes| G["Output Good"]
F -->|No| H["Check if score >= 60"]
H --> I{"Met?"}
I -->|Yes| J["Output Pass"]
I -->|No| K["Output Fail"]
D --> L["End"]
G --> L
J --> L
K --> L
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style K fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style L fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
3.3 for Loop Code Block
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(name)
print("正在处理用户")
print("循环结束")
The loop body following for is consistently indented one additional level.
After the loop ends, the original indentation level is restored.
3.4 while Loop Code Block
count = 0
while count < 3:
print(count)
count += 1
print("循环完成")
The code block for while is delimited by indentation, and its structure is the same as that of for.
3.5 Function Code Block
A function definition introduces a code block using def and a colon.
def calculate_total(price, quantity):
total = price * quantity
if total > 1000:
return total * 0.9
return total
All statements inside a function belong to the function code block unless they enter another nested code block.
3.6 Class Code Block
Class definitions likewise use indentation to organize attributes and methods.
class User:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, {self.name}")
Methods in a class belong to the code block of the class definition, and statements inside a method belong to the method code block.
4. Nested Code Blocks and Indentation Levels
A nested code block is a code block contained within another code block.
For example:
def process_users(users):
for user in users:
if user["active"]:
print(user["name"])
This contains three levels:
- Function code block.
- Loop code block.
- Conditional code block.
Each time a new code block is entered, one additional indentation level is added.
4.1 Multilevel Nested Structure
def check_access(user):
if user is not None:
if user["active"]:
if user["role"] == "admin":
print("管理员权限")
Corresponding indentation:
def check_access(user): 0 spaces
if user is not None: 4 spaces
if user["active"]: 8 spaces
if user["role"]: 12 spaces
print(...) 16 spaces
4.2 Avoid Deep Nesting
Excessive nesting reduces readability and increases the cost of understanding and maintenance.
Not recommended:
def process_user(user):
if user is not None:
if user["active"]:
if user["role"] == "admin":
if user["verified"]:
print("允许访问")
You can use early returns to reduce nesting:
def process_user(user):
if user is None:
return
if not user["active"]:
return
if user["role"] != "admin":
return
if not user["verified"]:
return
print("允许访问")
Early returns allow exceptional conditions to end as early as possible, keeping the core business logic at a shallower indentation level.
4.3 Execution Flow of Nested Structures
flowchart TD
A["Enter function"] --> B{"Does the user exist?"}
B -->|No| C["Return directly"]
B -->|Yes| D{"Is the user active?"}
D -->|No| C
D -->|Yes| E{"Is the user an admin?"}
E -->|No| C
E -->|Yes| F{"Is verification complete?"}
F -->|No| C
F -->|Yes| G["Perform admin operation"]
G --> H["End"]
C --> H
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
5. Python Empty Code Blocks and pass
Sometimes you need to define a function, class, or conditional branch first, but the concrete logic has not yet been implemented.
Python does not allow a code block to have no statements at all.
For example:
def do_something():
This produces a syntax error because the function body has no content.
In this case, you can use pass.
5.1 The Role of pass
pass is Python's no-op statement.
It can serve as a placeholder statement in a code block and does not perform any actual operation.
def do_something():
pass
5.2 Common Use Cases for pass
Function placeholder:
def create_user():
pass
Class placeholder:
class User:
pass
Conditional branch placeholder:
if condition:
pass
else:
print("条件不成立")
Exception handling placeholder:
try:
execute_task()
except Exception:
pass
The last form is syntactically valid, but silently ignoring all exceptions is usually not good practice. Production code should log, handle, or re-raise exceptions as required by the business logic.
5.3 Differences Between pass, continue, and break
These three keywords are easy to confuse.
| Keyword | Purpose | Ends the current loop |
|---|---|---|
| pass | Does nothing, acting as a placeholder statement | No |
| continue | Skips the remaining statements in the current iteration and moves to the next | The current iteration ends |
| break | Immediately exits the current loop | Yes |
Example:
for number in range(5):
if number == 1:
pass
if number == 2:
continue
if number == 4:
break
print(number)
Execution result:
0
1
3
Execution logic:
flowchart TD
A["Enter loop"] --> B["Get current number"]
B --> C{"number == 1"}
C -->|Yes| D["Execute pass"]
C -->|No| E{"number == 2"}
D --> E
E -->|Yes| F["continue skips remaining statements in this iteration"]
E -->|No| G{"number == 4"}
G -->|Yes| H["break exits loop"]
G -->|No| I["Execute print"]
I --> J["Enter next iteration"]
F --> J
J --> B
H --> K["Loop ends"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style K fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
6. Python's Underlying Indentation Mechanism
Python does not simply determine code blocks based on the number of spaces in the source code; it also processes indentation structure during lexical analysis.
In CPython, indentation is converted into special lexical tokens.
The most important are:
INDENT: indicates entering a new indentation level.DEDENT: indicates exiting one or more indentation levels.NEWLINE: indicates the end of a logical line.
These tokens help the later syntax analysis stage identify code block structure.
6.1 INDENT and DEDENT
For example:
if True:
print("Hello")
print("World")
Its structure can be conceptualized as:
IF
NAME(True)
COLON
NEWLINE
INDENT
NAME(print)
...
NEWLINE
DEDENT
NAME(print)
...
NEWLINE
Here:
INDENTindicates entering theifcode block.DEDENTindicates exiting theifcode block.
This is also why Python does not need to use braces to explicitly mark code block boundaries like C and Java do.
6.2 Marker changes with multi-level indentation
if True:
for number in range(3):
print(number)
print("Loop ends")
print("Program ends")
Conceptual indentation changes:
Top level
INDENT: enter if
INDENT: enter for
DEDENT: exit for
DEDENT: exit if
Top level
Note:
INDENTandDEDENTare structural markers produced by lexical analysis.- They are not keywords that can be written directly in Python source code.
- The specific parsing process belongs to Python implementation mechanisms; CPython's internal implementation details should not be directly generalized as how all Python implementations work.
6.3 Using tokenize to inspect indentation markers
The Python standard library provides the tokenize module, which can be used to inspect lexical tokens in source code.
import io
import tokenize
source = """
if True:
print("Hello")
print("World")
"""
tokens = tokenize.generate_tokens(
io.StringIO(source).readline
)
for token in tokens:
print(
tokenize.tok_name[token.type],
repr(token.string),
)
In the output, you can see tokens similar to the following:
NAME 'if'
NAME 'True'
OP ':'
NEWLINE '\n'
INDENT ' '
NAME 'print'
...
DEDENT ''
NAME 'print'
...
This can help you understand how Python identifies code blocks through indentation.
Seven. Difference Between Tabs and Spaces
Python allows tabs or spaces to represent indentation, but mixing them is not recommended.
PEP 8 recommends using spaces, with 4 spaces per indentation level.
7.1 Space indentation
if True:
print("Hello")
This is the recommended way to write it.
7.2 Tab indentation
if True:
print("Hello")
A tab can also represent indentation, but different editors may use different display widths for a tab.
7.3 Mixed indentation
if True:
print("Hello")
print("World")
This code mixes spaces and tabs, which may cause:
TabError: inconsistent use of tabs and spaces in indentation
7.4 Why mixed indentation is error-prone
Tabs and spaces are different characters in a text file.
Although an editor may display a tab as the width of 4 spaces, Python still needs to determine whether indentation levels are consistent when processing indentation.