常见场景一:循环语句
- 场景描述:在
for
或while
循环中,打算对循环体内的多行代码进行重复执行,但忘记对部分代码行进行缩进。例如:
for i in range(5):
print(i)
print('This should be part of the loop but isn\'t indented')
- 解决办法:仔细检查循环体需要包含的代码,确保所有要在循环内执行的代码都有相同的缩进,通常为4个空格(按照Python代码风格惯例)。修改后如下:
for i in range(5):
print(i)
print('This is now part of the loop')
常见场景二:条件语句
- 场景描述:在
if - elif - else
语句块中,当条件满足时需要执行多个操作,但部分代码未正确缩进。例如:
x = 10
if x > 5:
print('x is greater than 5')
print('This should be indented and part of the if block')
- 解决办法:确认条件语句块内需要执行的所有代码,统一缩进。如下修改:
x = 10
if x > 5:
print('x is greater than 5')
print('This is now part of the if block')
常见场景三:函数定义内部
- 场景描述:在函数定义内部有多行代码逻辑,但部分代码行没有缩进为函数体的一部分。例如:
def my_function():
print('Start of function')
print('This should be part of the function but isn\'t indented')
- 解决办法:确保函数体中的所有代码都相对于函数定义有正确的缩进。修改后:
def my_function():
print('Start of function')
print('This is now part of the function')