Python代码中total_costs自定义函数无法正常运行求助
代码运行失败的核心原因
- 变量作用域不匹配:你在
get_input()函数内部定义的e1~e5都是局部变量,仅在get_input()函数的执行生命周期内有效,total_costs()函数没有权限直接访问另一个函数内部的局部变量,执行求和操作时会直接报变量未定义错误。 - 函数调用逻辑错误:你全程没有主动调用过
total_costs()函数,哪怕作用域规则允许,get_input()里用到的monthly和yearly变量也不存在,执行get_input()时同样会触发变量未定义报错。
修复后的参考代码
采用参数传值的规范写法,将采集到的支出数据传入计算函数:
def get_input(): e1 = float(input("What is the monthly expense for House Payment. ")) e2 = float(input("What is the monthly expense for Homeowners Insurance. ")) e3 = float(input("What is the monthly expense for Car Payments. ")) e4 = float(input("What is the monthly expense for Car Insurance. ")) e5 = float(input("What is the monthly expense for Utilities. ")) # 调用计算函数传入参数,接收返回的计算结果 monthly, yearly = total_costs(e1, e2, e3, e4, e5) print("The monthly expenses total to",format(monthly, ',.2f')) print("The yearly expenses total to",format(yearly, ',.2f')) def total_costs(e1, e2, e3, e4, e5): monthly = e1 + e2 + e3 + e4 + e5 yearly = monthly * 12 return monthly, yearly get_input()
内容的提问来源于stack exchange,提问作者LastCheck
相关产品推荐
相关产品推荐

