首页 > 解决方案 > 如何覆盖 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 上?当我查看其他计算器代码并且我的看起来相同时,这让我感到困惑。

标签: pythonfunctionif-statement

解决方案


您的问题是您使用 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)

推荐阅读