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

Python递归调用后函数返回值丢失为None问题排查

温度转换器函数返回值异常问题

问题表现

  • 输入错误单位值(如"celsiuss"、"klevin")时,程序进入else分支,提示输入有效单位后回到函数起始处重新执行,该行为符合预期
  • 重新输入有效单位后,程序进入对应if分支返回目标值,但退出函数后返回值变为None
  • 断点调试确认递归调用内部return时inputUnitSelection的值为1(对应Celsius),但最外层函数返回值为None,print打印结果与调试结论一致,导致inputUnit变量无有效值,后续代码无法运行
  • 若首次直接输入有效单位,函数可正常返回正确值,全流程运行无异常

问题复现代码

Celsius = 1
Farenheit = 2
Kelvin = 3

def inputUnitSelection():
    unitInput = input(
        "What is the unit of the temperature you wish to convert ? (Celsius, Farenheit, Kelvin) \n")
    
    if(unitInput == "Celsius" or unitInput == "celsius"):
        return Celsius 
    elif(unitInput == "Farenheit" or unitInput == "farenheit"):
        return Farenheit 
    elif(unitInput == "Kelvin" or unitInput == "kelvin"):
        return Kelvin 
    else:
        print("This is not an unit. Please enter a valid unit. \n")
        inputUnitSelection()

inputUnit = inputUnitSelection()

问题根因

else分支仅调用了递归函数,没有将递归调用的返回值向外传递。当输入错误触发递归时,当前层级的函数执行完打印、递归调用两个步骤后就运行结束,没有显式return语句,Python函数无显式返回值时默认返回None。内层递归拿到的正确值仅在内层函数作用域生效,没有逐层传递到最外层调用,因此最终赋值结果为None。只有首次输入直接命中有效单位分支时,函数才会走到显式return逻辑返回正确值,这也是两种输入场景表现不一致的原因。

修复方案

在else分支的递归调用前添加return关键字,将内层递归的返回值逐层传递到最外层即可。
修改后的else分支代码如下:

else:
        print("This is not an unit. Please enter a valid unit. \n")
        return inputUnitSelection()

注:这类输入重试场景更推荐使用while循环实现,递归写法在连续多次输错的极端场景下存在栈溢出风险,不过添加return后当前写法功能可正常运行。

内容的提问来源于stack exchange,提问作者Yann

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 04:36:23