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

为何Python在错误输入后输入合法值时会返回None?

问题分析:递归函数返回值缺失导致的None问题

原代码

def force_input(type):
    try:
        return type(input())
    except ValueError:
        print(f'Input must be {type}')
        force_input(type)

number = force_input(int)
print(number)

问题现象

  • 首次输入整数时,代码正常输出该整数;
  • 若先输入非整数(如lettuce),会正常提示Input must be <class 'int'>,但后续输入整数9时,输出结果为None而非9。

原因解析

问题出在递归调用时没有返回结果:当触发ValueError异常后,函数执行了force_input(type)递归调用,但这个递归调用的返回值没有被return出去。此时外层的force_input函数在异常分支执行完后,没有任何返回语句,Python会默认返回None,最终导致变量number的值为None。

修复后的代码

只需要在异常分支的递归调用前加上return,把递归的结果传递回去:

def force_input(type):
    try:
        return type(input())
    except ValueError:
        print(f'Input must be {type}')
        return force_input(type)  # 加上return,传递递归返回值

number = force_input(int)
print(number)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 01:19:50