Python WeightConverter递归调用后返回None如何解决
问题原因
核心问题是else分支中递归调用convertWeight时,没有将递归的返回值向外返回。当用户首次输入无效单位时,最外层的函数执行完else块的逻辑就直接终止了,没有触发显式return,Python函数无显式返回时默认返回None,最终拿到的output就是None。
另外递归调用时直接传入了全局变量givenWeight,没有使用函数形参接收的weight参数,会破坏函数独立性,后续复用时容易出逻辑错误。
修复方案
只需要在递归调用前加上return关键字,同时修正传入的重量参数为当前函数的形参即可:
givenWeight = int(input("Weight? ")) unit = input("lbs or kgs? ") converted = 0 def convertWeight(weight, unit): if unit == "lbs": converted = f"{weight * 0.454} kgs" return converted elif unit == "kgs": converted = f"{weight * 2.205} lbs" return converted else: print("Invalid unit") unit = input("lbs or kgs? ") # 返回递归调用的结果,传入当前形参weight而非全局变量 return convertWeight(weight, unit) output = convertWeight(givenWeight, unit) print(output)
可选优化(循环写法)
如果觉得递归逻辑不好理解,也可以用循环直接在函数内校验用户输入,直到输入合法再做转换,逻辑更直观:
givenWeight = int(input("Weight? ")) unit = input("lbs or kgs? ") def convertWeight(weight, unit): # 循环校验单位合法性 while unit not in ("lbs", "kgs"): print("Invalid unit") unit = input("lbs or kgs? ") if unit == "lbs": return f"{weight * 0.454} kgs" else: return f"{weight * 2.205} lbs" output = convertWeight(givenWeight, unit) print(output)
内容的提问来源于stack exchange,提问作者Illusioner_
相关产品推荐
相关产品推荐

