Python编写简易计算器时while循环校验运算符逻辑问题如何解决?
代码问题修复方案
你现有代码的核心问题如下:
- 条件判断逻辑错误:你写的
while operation != '+' or '-' or '*' or '/' or '^'不符合Python语法逻辑,非空字符串的布尔值恒为True,所以这个条件不管输入任何内容都会判定为成立,永远触发错误提示。 - 循环流程缺失:循环体里直接加了
break,只会执行一次提示就退出,不会重复校验输入,也没有在循环中重新获取用户输入的运算符。 - while...else搭配逻辑错误:现有代码的else分支绑定在while上,只有循环未被break中断时才会执行,和你要的“校验通过后执行计算”的逻辑不匹配。
修复后的完整代码如下:
n1 = int(input("Enter first number: ")) n2 = int(input("Enter second number: ")) def add(n1,n2): return n1 + n2 def sub(n1,n2): return n1 - n2 def div(n1,n2): return n1 / n2 def mult(n1,n2): return n1 * n2 def exp(n1,n2): return n1 ** n2 print("Choose operation (+, -, *, /, ^): ") operation = input() # 定义合法运算符集合 valid_ops = {'+', '-', '*', '/', '^'} # 只要输入不在合法集合中,就循环要求重新输入 while operation not in valid_ops: print("Invalid operation, try again (+, -, *, /, ^): ") operation = input() # 校验通过后执行对应计算 if operation == '+': print(n1,"+",n2,"=",add(n1,n2)) elif operation == '-': print(n1,"-",n2,"=",sub(n1,n2)) elif operation == '*': print(n1,"*",n2,"=",mult(n1,n2)) elif operation == '/': print(n1,"/",n2,"=",div(n1,n2)) elif operation == "^": print(n1,"^",n2,"=",exp(n1,n2))
内容的提问来源于stack exchange,提问作者Gus998
相关产品推荐
相关产品推荐

