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

Python函数触发异常后返回None的问题修复咨询

修复递归调用导致返回None的问题

你的代码在输入非法值后递归调用exception()时,没有将递归得到的正确结果返回给上层调用,所以第一次出错的函数调用最终返回了None,导致列表里出现[None, 2]这种情况。

修复方法

在两个except块的递归调用前加上return,让递归获取到的正确数值能传递回最初的函数调用。同时可以优化变量名和函数名提升代码可读性:

class NotPositiveError(Exception):
    pass

lengths_list = []  # 修正原拼写错误lenghts -> lengths

def get_positive_number():  # 函数名改为更具语义的名称
    try:
        user_num = int(input("Put a number: "))
        if user_num > 0:
            return user_num
        else:
            raise NotPositiveError
    except ValueError as err:
        print(err)
        return get_positive_number()  # 添加return传递递归结果
    except NotPositiveError:
        print("Sorry, your input should be positive")
        return get_positive_number()  # 添加return传递递归结果

print("Put two numbers. The first is for the size of your main list and the second is for the size of the operator lists ")
for i in range(2):
    user_length = get_positive_number()
    print(user_length)
    lengths_list.append(user_length)
print(lengths_list)

关键修改说明

  • 原代码中except块仅调用递归但未返回结果,导致最初的函数调用没有拿到正确值,最终返回None。添加return后,递归得到的正整数会逐层传递回最外层调用,正确赋值给user_length。
  • 修正了变量名拼写错误lenghts_list,并重命名函数为get_positive_number,让代码逻辑更清晰。

内容的提问来源于stack exchange,提问作者yousof A.Asadi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:06:05