Python代码运行报netpay not defined错误的问题求助
错误原因排查
- 变量未拆包接收:
get_income()会返回comission、Gpay、deductions、netpay四个值,你只把返回结果存在了income元组里,没有拆包赋值给对应变量,main函数作用域找不到单独的netpay等变量,直接调用就会报未定义错误。 - 函数定义顺序错误:
get_info、get_income、get_budget三个内部函数的定义放在了调用逻辑之后,Python从上到下执行代码时,调用函数时函数还没完成定义,会触发未定义报错。 - 变量拼写错误:
get_budget函数内部定义的是HnC,返回时写的是小写的Hnc,大小写不匹配会触发未定义报错。 - 无限递归问题:main函数末尾又调用了一次
main(),执行后会进入无限递归,最终触发递归深度超限报错。 - 可选业务逻辑修正:你当前的总薪资计算写的是
Gpay=BASE_PAY*comission,通常底薪加提成的计算逻辑应该是Gpay=BASE_PAY+comission,可以自行核对业务规则调整。
修正后可运行代码
BASE_PAY=900 total_sale=float(input('What\'s your total sale?: ')) def main(): # 先定义所有内部函数 def get_info(): Fname=input('Enter your first name: ') Lname=input('Enter your last name: ') gender=input('Please enter your gender(m/f): ') if gender.lower() == 'm': print('Mr.',Fname,Lname) else: print('Ms.',Fname,Lname) return Fname, Lname, gender def get_income(): comission=total_sale*0.06 # 这里如果确实是底薪乘佣金的规则可以改回* Gpay=BASE_PAY + comission deductions=Gpay*0.18 netpay=Gpay-deductions return comission, Gpay, deductions, netpay def get_budget(netpay): HnC=netpay*0.45 FnC=netpay*0.20 entertainment=netpay*0.25 misc=netpay*0.10 # 修正拼写错误 return HnC,FnC, entertainment, misc # 执行调用逻辑,拆包接收所有返回值 demographics=get_info() comission, Gpay, deductions, netpay = get_income() HnC, FnC, entertainment, misc = get_budget(netpay) print('Total sales is: $',total_sale) print('Your comission is: $',comission) print('The gross pay is: $',Gpay) print('The deductions are: $',deductions) print('The netpay is: $',netpay) print('Housing & Utility: $', HnC) print('Food & Clothing: $', FnC) print('Entertainment: $', entertainment) print('Miscellaneous costs: $', misc) # 外部调用main函数,避免内部递归 if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者taifhamid1
相关产品推荐
相关产品推荐

