You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何两段相似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

为什么第二段能正常运行

  1. 递归条件永远不触发:iandj()返回的i固定为10,10%2==0,所以if i%2!=0的分支永远不会执行,函数不会进入递归,直接执行else分支填充a后返回,主程序能拿到正确的非空列表。
  2. 即使假设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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 23:36:16