main函数第三个elif分支触发UnboundLocalError问题求助
问题解决:选择3-Both服务时触发UnboundLocalError
错误根源
在main函数的第三个elif分支(对应3-Both服务)中,变量名拼写错误:将totalcost误写为toatlcost,导致后续调用SeniorDiscount(totalcost)时,totalcost未被定义,直接触发UnboundLocalError。
此外还有两个潜在问题会影响程序逻辑:
homeservice函数中,当房间数在3-6之间时,调用LC或DC后未将返回值赋值给totalcost就直接return totalcost,会导致返回None。SeniorDiscount函数的else分支中,递归调用自身后未返回递归结果,可能导致折扣计算异常。
修复步骤
1. 修正main函数的变量拼写错误
将第三个elif分支里的toatlcost改为正确的totalcost:
elif YHB == 3: totalcost = homeservice() + YardService() SeniorDiscount(totalcost)
2. 修复homeservice函数的return逻辑
在房间数3-6的分支中,将LC/DC的返回值赋值给totalcost后再返回:
elif 3 < NumberOfRooms < 6: print("Your starting total is: $", 175) CostOfRooms = 175 windows = eval(input("How many windows do you have in need of cleaning?\n")) CostOfWindows = 10 TypeClean = eval(input("What kind of cleaning service are you in search of?\n1-Light Cleaning\n2-Deep Cleaning\n")) if TypeClean == 1: totalcost = LC(CostOfRooms,windows) return totalcost elif TypeClean == 2: totalcost = DC(CostOfRooms,windows) return totalcost else: print("You must select a service in order to continue")
3. 修复SeniorDiscount函数的递归返回问题
在else分支中,返回递归调用的结果,确保折扣逻辑正常传递:
else: print("We'll need an actual answer from you in order to continue") return SeniorDiscount(totalcost)
修复后的main函数完整片段
def main(): print("We'll start by asking you a set of questions") YHB = eval(input("What kind of cleaning service are you in search of?\n1-Home Service\n2-Yard Service\n3-Both\n")) if YHB == 1: totalcost = homeservice() SeniorDiscount(totalcost) elif YHB == 2: totalcost = YardService() SeniorDiscount(totalcost) elif YHB == 3: totalcost = homeservice() + YardService() SeniorDiscount(totalcost) else: print("You must have selected nothing, we'll try again.") main()
内容的提问来源于stack exchange,提问作者Creator Combat
相关产品推荐
相关产品推荐

