python - 如何覆盖 if 语句中的函数?
问题描述
我是 Python 新手,我只是在尝试创建一个简单的计算器,由于某种原因,一个函数不会被覆盖。无论我输入什么运算符,结果都将保持不变,为 3125。
我尝试使用百分比符号,但它仍然停留在一个输出上。
num1 = float(input("First Number: "))
op = input("Operator: ")
num2 = float(input("Second Number: "))
if op == "^" or "**":
result = float(num1) ** float(num2)
print("Result: %s" % result)
elif op == "/"or "÷":
result = float(num1) / float(num2)
print("Result: %s" % result)
elif op == "x" or "*" or ".":
result = float(num1) * float(num2)
print("Result: %s" % result)
elif op == "+":
result = float(num1) + float(num2)
print("Result: %s" % result)
elif op == "-":
result = float(num1) - float(num2)
print("Result: %s" % result)
为什么卡住了,为什么卡在 3125 上?当我查看其他计算器代码并且我的看起来相同时,这让我感到困惑。
解决方案
您的问题是您使用 or 作为任一符号,但or
每一侧都需要一个布尔运算符。
# change this
if op == "^" or "**":
# to this
if op == "^" or op == "**":
更好的是使用in
带有潜在选项列表的运算符。
if op in ['^', '**']:
如下更新您的代码,您应该一切顺利!我还删除了多余的行。因此,如果您想稍后更新它,您只需更新一次而不是 5 次。
if op in ["^" , "**"]:
result = float(num1) ** float(num2)
elif op in ["/", "÷"]:
result = float(num1) / float(num2)
elif op in ["x" , "*" , "."]:
result = float(num1) * float(num2)
elif op in ["+"]:
result = float(num1) + float(num2)
elif op in ["-"]:
result = float(num1) - float(num2)
print("Result: %s" % result)
推荐阅读
- python - 如何遍历由 getter 或 @property 定义的对象的属性?
- java - 这两种从 LocalDateTime 创建 DateTime 的方法有什么区别?
- perl - 如何拆分多个文件名并在输出中获取姓氏
- laravel - Laravel:`php artisan app:name MyApp` 导致异常:内核不存在
- javascript - 当函数稍后出现错误时,console.log 不起作用
- visual-studio - 如何在 Visual Studio 中测量 Fortran 代码指标?
- excel - 如何更改选定单元格的值?
- spring-cloud - 将 Zuul、Hystrix(和 Feign)与 Spring Cloud HATEOAS 一起使用时如何转发标头?
- javafx - 如何设置组合框的文本颜色?
- corda - 如何解决 Corda 4 升级中的“找不到合同附件”异常