Python while循环无法正常运行,请求故障排查与修复方案
问题修复方案
你的判断完全正确——循环里只重新获取了c_or_nc,但没根据新输入更新continue_变量,所以它一直保持True,循环根本停不下来。另外代码里还有个隐藏问题:result变量没做任何计算就直接打印,运行时会触发NameError,这个也得一起修。
修复后的完整代码
c_or_nc = input('Do you want to continue? (Yes/No): ') continue_ = c_or_nc.strip().lower() == 'yes' # 直接赋值,同时兼容大小写和首尾空格 while continue_: # 计算结果的逻辑 n1 = float(input('Please, enter a number: ')) op = input('Enter an operator (+, -, *, /, ^): ') n2 = float(input('Enter a second number: ')) # 根据运算符计算result if op == '+': result = n1 + n2 elif op == '-': result = n1 - n2 elif op == '*': result = n1 * n2 elif op == '/': # 加个除零判断更健壮 if n2 == 0: print('Error: Cannot divide by zero!') continue result = n1 / n2 elif op == '^': result = n1 ** n2 else: print('Invalid operator! Please use +, -, *, /, ^') continue print(f'The result is: {result}') # 获取新输入后立即更新continue_变量 c_or_nc = input('Do you want to continue? (Yes/No): ') continue_ = c_or_nc.strip().lower() == 'yes' # 循环结束后直接打印退出提示,不需要第二个while print('Alright! Have a nice day :).')
关键修改点
- 更新continue_变量:在循环内获取新的
c_or_nc后,立刻根据输入更新continue_的值,这样下一次循环判断时会生效 - 补充result计算逻辑:新增运算符分支处理,避免未定义变量报错,还加了除零判断和无效运算符提示
- 简化输入判断:用
strip().lower()处理输入,用户输入YES、yes、Yes这类格式都能正确识别,提升容错性 - 移除多余的while循环:原代码第二个
while continue_ is False完全没必要,循环结束后直接打印提示即可
内容的提问来源于stack exchange,提问作者Lyo
相关产品推荐
相关产品推荐

