Python程序返回None问题求助:嵌套tax函数未正确返回税费值
问题排查与修复
问题根源
你写的代码里外层tax函数内部定义了一个同名的嵌套tax函数,但外层函数没有返回任何值(也没有调用这个嵌套函数),Python中函数如果没有显式return语句,默认返回None,这就是你得到None的原因。而且这个嵌套函数完全是冗余的,没必要这么写。
修复后的代码(推荐方案)
直接把税费计算逻辑写在顶层tax函数中,去掉嵌套:
def tax(price): if price > 100000: return float(price * 20 / 100) elif 75000 < price <= 100000: return float(price * 15 / 100) elif 50000 < price <= 75000: return float(price * 10 / 100) else: return float(price * 5 / 100) price = int(input()) print(tax(price))
可选方案(保留嵌套,不推荐)
如果非要用嵌套函数,需要重命名内层函数避免冲突,同时外层函数调用内层函数并返回结果:
def tax(price): def calculate_tax(p): if p > 100000: return float(p * 20 / 100) elif 75000 < p <= 100000: return float(p * 15 / 100) elif 50000 < p <= 75000: return float(p * 10 / 100) else: return float(p * 5 / 100) return calculate_tax(price) price = int(input()) print(tax(price))
内容的提问来源于stack exchange,提问作者sbaredd
相关产品推荐
相关产品推荐

