Python实现计算器执行2.0-2.0时报运算符无效错误如何解决
问题产生原因
Python的布尔类型bool是整型int的子类,False对应的底层数值为0,做等值判断时0.0 == False的返回结果为True。当执行2.0 - 2.0运算时,solution被赋值为0.0,后续的if solution == False判断会把合法的0值结果误判为操作符无效,触发错误提示。
额外说明:你代码中遍历operations列表的循环属于冗余逻辑,无实际作用,可以直接删除。
修复方案
可选以下任意一种方案修复:
- 方案1:单独新增变量标记操作符合法性,避免用和数值结果可能重合的
False作为标记,同时删除冗余循环逻辑:
print("Whats your first number?") num1 = float(input()) print("Whats your second number?") num2 = float(input()) print("""Whats your operator? 1. Multiplication 2. Addition 3. Division 4. Subtraction """) operator = int(input()) solution = 0 is_operator_valid = True if operator == 1: solution = num1 * num2 elif operator == 2: solution = num1 + num2 elif operator == 3: solution = num1 / num2 elif operator == 4: solution = num1 - num2 else: is_operator_valid = False if not is_operator_valid: print("The operator is invalid. Please, try again.") else: print(solution)
- 方案2:不新增变量,仅修改最后的判断逻辑,用
is替代==判断是否为False。is会校验对象的身份而非数值,0.0 is False的返回结果为False,不会产生误判:
# 仅需要修改最后的判断语句即可 if solution is False: print("The operator is invalid. Please, try again.") else: print(solution)
内容的提问来源于stack exchange,提问作者Anonymous Man
相关产品推荐
相关产品推荐

