Python报错TypeError:无法解包NoneType对象,明明已返回值
问题分析与解决
核心问题
你的search函数在递归分支(elif savings < required_down和else块)中调用了search(),但没有将递归调用的结果返回。这会导致当程序进入这些分支时,函数执行完递归后没有返回任何值,默认返回None,而调用方userInput()试图将None解包成两个变量,因此触发TypeError。
修复代码
修改search函数的递归分支,添加return关键字传递递归结果:
def search(start, end, step, salary, savings, r, required_down, semi, months): test_value = (start+end)/2 original_salary = salary while savings <= required_down and months <= 36: if months != 0 and months%6 == 0: salary *= 1+semi savings += (savings*r/12) + (salary/12)*(test_value/10000) months+=1 if required_down - 500 < savings < required_down + 500: return test_value, step elif savings < required_down: savings = 0 months = 0 # 添加return传递递归结果 return search(test_value, end, step + 1, original_salary, savings, r, required_down, semi, months) else: savings = 0 months = 0 # 添加return传递递归结果 return search(start, test_value, step + 1, original_salary, savings, r, required_down, semi, months) if step >= 25: rate = 'n/a' steps = 'n/a' return rate,steps
额外优化说明
- 你原本的
step >=25判断逻辑永远不会被执行,因为前面的if/elif/else已经覆盖了所有情况,属于不可达代码。建议将递归终止条件移到函数开头,避免逻辑冗余:
def search(start, end, step, salary, savings, r, required_down, semi, months): # 优先检查递归终止条件 if step >= 25: return 'n/a', 'n/a' test_value = (start+end)/2 original_salary = salary current_savings = savings current_months = months while current_savings <= required_down and current_months <= 36: if current_months != 0 and current_months % 6 == 0: salary *= 1 + semi current_savings += (current_savings * r / 12) + (salary / 12) * (test_value / 10000) current_months += 1 if required_down - 500 < current_savings < required_down + 500: return test_value / 10000, step # 直接返回实际利率,无需调用方额外转换 elif current_savings < required_down: return search(test_value, end, step + 1, original_salary, 0, r, required_down, semi, 0) else: return search(start, test_value, step + 1, original_salary, 0, r, required_down, semi, 0)
内容的提问来源于stack exchange,提问作者ted
相关产品推荐
相关产品推荐

