Python简易计算器开发:如何校验用户输入的合法操作符?
简易计算器操作符校验问题修复
版本一的核心错误
你在第一个版本里的操作符判断逻辑用错了逻辑运算符:
if operand != '/' or operand != '*' or operand != '+' or operand != '-':
这个条件永远为真——比如输入+时,operand != '/'是True,or逻辑只要有一个判断为真,整体就为真,所以不管输入什么合法操作符,都会触发错误提示并回到循环开头。
正确逻辑应该是:当操作符同时不等于所有合法选项时才触发错误,要么把or改成and,要么用更简洁的not in判断:
# 写法一:修正逻辑运算符 if operand != '/' and operand != '*' and operand != '+' and operand != '-': # 写法二(推荐):用in简化判断 if operand not in ['+', '-', '*', '/']:
版本二的核心错误
第二个版本里直接把单个字符串和列表做相等比较:
if operand != listOfOperands:
单个操作符字符串永远不可能等于列表['+', '-', '/', '*'],导致所有输入都会被判定为非法。正确写法是检查操作符是否不在合法列表中:
if operand not in listOfOperands:
修正后的完整代码
下面是优化后的版本,兼顾可读性和正确性:
calc = False while not calc: first_num = 0 operand = '' second_num = 0 valid_operands = ['+', '-', '*', '/'] # 处理第一个数字输入 first_input = input('请输入第一个数字: ') if not first_input.isdigit(): print('请输入有效的数字。') continue first_num = int(first_input) # 校验操作符 operand = input('请输入操作符 (+, -, *, /): ') if operand not in valid_operands: print('请输入有效的操作符。') continue # 处理第二个数字输入 second_input = input('请输入第二个数字: ') if not second_input.isdigit(): print('请输入有效的数字。') continue second_num = int(second_input) # 处理除零异常 if operand == '/' and second_num == 0: print('不能除以0,请重新尝试。') continue # 计算并输出结果 if operand == '+': result = first_num + second_num elif operand == '-': result = first_num - second_num elif operand == '*': result = first_num * second_num else: result = first_num / second_num print(f'{first_num} {operand} {second_num} = {result}') calc = True
内容的提问来源于stack exchange,提问作者Ant753
相关产品推荐
相关产品推荐

