Python百分比计算器调用exit()无法退出的问题求助
问题分析与解决
你的百分比计算器无法在输入n后退出,核心问题及修复方案如下:
1. 字符串方法调用错误
代码里value.lower == "y"和value.lower == "n"是错误写法:lower是字符串的方法,必须加括号()才能调用并返回小写后的字符串。当前写法是把方法对象和字符串做比较,永远不会相等,自然触发不了exit()分支。
2. 循环逻辑冗余
输入y时直接调用percentage(),但外层已有while True循环,会导致连续两次执行计算逻辑,属于冗余操作,改用continue让循环回到开头即可。
另外,用break替代exit()退出循环更符合Python代码风格,避免直接终止解释器。
修正后的完整代码
def percentage(): numbers = [] x = int(input('How many subjects would you like to find the percentage for:')) for i in range(x): n = int(input('subject ' + str(i+1) + ': ')) numbers.append(n) final = sum(numbers) / len(numbers) print("The percentage is", final, "%") while True: try: percentage() value = input("Do you want to calculate again (y/n):") if value.lower() == "y": continue # 回到循环开头,重新执行计算 elif value.lower() == "n": print("ok, sayonara") break # 退出循环,程序结束 else: print("Invalid input, please enter y or n") except ValueError: # 捕获具体错误类型,避免隐藏未知问题 print("\nOops! Please enter valid numbers. Try again...\n")
额外建议:不要用except:捕获所有异常,这会隐藏键盘中断(Ctrl+C)等操作,应该捕获具体异常类型(比如ValueError处理输入非数字的情况)。
内容的提问来源于stack exchange,提问作者SK-the-Learner
相关产品推荐
相关产品推荐

