Python开发:如何避免if分支重复调用benefit_calc()函数?
解决重复调用函数导致重复输入的问题
核心问题是你在income_bracket_calc函数的1-5000薪资区间分支里,每次执行if/elif判断时都会重复调用benefit_calc()函数,而该函数包含用户输入语句,导致程序反复弹出询问。只需先调用一次函数并保存结果,后续判断直接使用这个结果即可。
修改方案:
- 在进入判断逻辑前,调用一次
benefit_calc(),将返回值存入变量 - 所有if/elif的判断条件改为使用这个变量,不再重复调用函数
- 删除分支中多余的单独调用
benefit_calc()语句(原代码中该行只会触发一次无意义的询问)
修改后的完整代码:
def tax_calc(tax: float, tax_perc: int): tax_pay = tax * (tax_perc / 100) return tax_pay def income_bracket_calc(user_sal: float): def benefit_calc(): user_child_input = input("Do you have any children? (y/n): ") if user_child_input == "y": return 1 elif user_child_input == "n": return 2 else: return 3 if user_sal <= 0: print("Invalid input. Please Select y/n only.") elif 1 <= user_sal <= 5000: # 仅调用一次函数并保存结果 benefit_result = benefit_calc() if benefit_result == 1: print("You have qualified for free medical aid and a 100% school bursary for your children.") print("You do not have to pay income tax.") print() elif benefit_result == 2: print("You have qualified for free medical aid.") print("You do not have to pay income tax.") print() elif benefit_result == 3: print("Invalid input. Please use y/n only.") print() elif 5001 <= user_sal <= 10000: print() elif user_sal > 10000: print() while True: user_income_input = float(input("Please enter your income: ")) income_bracket_calc(user_income_input) kill_prg = input("Would you like to exit the program? y/n: ") if kill_prg == "y": break elif kill_prg == "n": continue else: print("Invalid input. Use y/n only.")
内容的提问来源于stack exchange,提问作者Duimpie
相关产品推荐
相关产品推荐

