Python交互式计算器无结果输出且自动重启的问题求助
Python交互式计算器无结果输出且自动重启的问题求助
嗨,我来帮你排查下问题所在,你的代码有几个关键逻辑和语法错误,导致了现在的现象:
问题1:异常处理写法完全错误
你第二个try-except块的写法不符合Python语法:
try: function = input('Please choose operation from [+, -, *, /]: ') except function not in allowed_functions: print(f'Function must contain mathetmatical operation values only') continue
except后面只能跟异常类型(比如ValueError),而function not in allowed_functions是一个普通的逻辑判断,不是异常。正确的做法是先获取输入,再用if来检查:
function = input('Please choose operation from [+, -, *, /]: ') if function not in allowed_functions: print(f'Function must contain mathematical operation values only') continue
问题2:return语句导致结果无法显示且循环提前终止
你在格式化完结果后直接return problems,这会立刻退出整个solver()函数:
- 首先,你没有打印这个返回的结果,所以用户看不到任何输出;
- 其次,
return会直接跳出函数,导致后面的退出询问代码(quit_program = input(...))永远不会被执行,循环也会被打断。
问题3:循环逻辑无法支持多次计算或正常退出
因为return的存在,你的while True循环实际上无法完成完整的“计算-询问退出”流程,要么遇到错误继续循环,要么计算完直接退出函数。
修复后的完整代码
def solver(): while True: # 获取第一个数字 try: arg1 = float(input('Add 1st number: ')) arg2 = float(input('Add 2nd number: ')) except ValueError: print('Invalid input. Please enter a number') continue allowed_functions = set(['+', '-', '/', '*']) # 获取并验证运算符号 function = input('Please choose operation from [+, -, *, /]: ') if function not in allowed_functions: print(f'Function must contain mathematical operation values only') continue # 计算结果 output = None if function == '+': output = arg1 + arg2 elif function == '-': output = arg1 - arg2 elif function == '*': output = arg1 * arg2 elif function == '/': if arg2 == 0: print(f'Division by 0 not possible') continue else: output = arg1 / arg2 # 格式化输出 str_arg1 = str(arg1) str_arg2 = str(arg2) str_output = str(output) width = max(len(str_arg1), len(str_arg2)) + 2 top = str_arg1.rjust(width) bottom = function + str_arg2.rjust(width-1) lines = '-' * width result = str_output.rjust(width) # 打印结果 print(f'{top}\n{bottom}\n{lines}\n{result}') # 询问是否退出 quit_program = input('Quit Program? Y/N: ') if quit_program.upper() == 'Y': break solver()
关键修改说明
- 把错误的
try-except改成if判断来验证运算符号; - 移除了
return,改成直接打印格式化后的计算结果,这样你能看到输出; - 把退出询问移到打印结果之后,确保每次计算完成后都能选择退出或继续;
- 使用
quit_program.upper()来统一判断,不管用户输入大写还是小写Y都能识别; - 给
output初始化了None,避免潜在的未定义问题。
现在运行代码,计算完成后会显示格式化的结果,然后询问你是否退出,选择Y就结束程序,选择N会回到输入数字的步骤继续计算~
内容来源于stack exchange
相关产品推荐
相关产品推荐

