为何两段相似Python递归代码一段报IndexError一段正常?
递归函数返回值错误分析:两段代码的差异与报错原因
问题概述
两段结构相似的Python递归代码,第一段中checkinputs()函数在满足条件时可正常打印round_desc_list[0],但主程序调用该函数后打印该元素却抛出IndexError: list index out of range;第二段代码逻辑类似却能正常运行,现分析两者差异及报错原因。
第一段代码与报错分析
代码片段
def checkinputs(): desc_list = [] round_desc_list = [] time.sleep(30) event_type = "input" event,output_list,desc_list,psbt,num_i = getevents() if num_i % 5 !=0 or num_i == 0: print(num_i) checkinputs() # 问题核心:递归调用未返回结果 else: round_desc_list.append(desc_list[0]) round_desc_list.append(desc_list[1]) round_desc_list.append(desc_list[2]) round_desc_list.append(desc_list[3]) round_desc_list.append(desc_list[4]) print(round_desc_list[0]) print("\n5 inputs registered\n") return round_desc_list,num_i if __name__=="__main__": while True: event_type = "input" round_desc_list,num_i = checkinputs() break print(round_desc_list[0])
报错信息
desc1 5 inputs registered Traceback (most recent call last): print(round_desc_list[0]) IndexError: list index out of range
报错原因
问题出在递归调用未传递返回值:
- 当
num_i %5 !=0或num_i==0时,函数会递归调用checkinputs(),但这个递归调用的返回值(填充后的round_desc_list和最终的num_i)没有被赋值给当前函数的变量。 - 递归层级中,只有最底层满足
num_i%5==0的那个函数会填充round_desc_list并打印,但它的返回值不会传递给上层调用的函数。上层函数的round_desc_list始终是初始的空列表,最终返回给主程序的就是这个空列表,因此主程序访问round_desc_list[0]时触发索引越界错误。 - 函数内部打印的
round_desc_list[0]是最底层递归函数的局部变量,和上层函数返回的空列表无关,所以能正常输出。
第二段代码对比分析
代码片段
import time def iandj(): i=0 j=[] while i<10: j.append(i) i+=1 return j,i def fun(): a = [] j,i= iandj() time.sleep(5) if i % 2 !=0: fun() else: a.append(j[0]) a.append(j[1]) return a,i if __name__=="__main__": while True: a,i = fun() break print(a[0]) print(i)
运行结果
0 10
为什么第二段能正常运行
- 递归条件永远不触发:
iandj()返回的i固定为10,10%2==0,所以if i%2!=0的分支永远不会执行,函数不会进入递归,直接执行else分支填充a后返回,主程序能拿到正确的非空列表。 - 即使假设
i为奇数(比如修改iandj()的逻辑),第二段同样会出现和第一段一样的错误——因为递归调用fun()时同样没有传递返回值,上层函数的a还是空列表。但由于当前逻辑下递归不会触发,所以没有暴露这个问题。
修复方案
修改第一段代码的递归调用部分,将递归返回的结果赋值给当前函数的变量:
if num_i % 5 !=0 or num_i == 0: print(num_i) round_desc_list, num_i = checkinputs() # 接收递归返回值
这样,上层函数就能获取到最底层递归填充后的round_desc_list,主程序调用时就不会出现索引越界错误。
内容的提问来源于stack exchange,提问作者user18991902
相关产品推荐
相关产品推荐

