Python基本计算器程序不返回答案

时间:2016-05-01 22:07:06

标签: python calculator

所以我试图弄清楚如何使用我在python中学到的东西来制作一个计算器,但我不能让它给我一个答案。

这是我到目前为止的代码:

def add(x, y):
    return x + y

def subtract (x, y):
    return x - y


def divide (x, y):
    return x / y


def multiply (x, y):
    return x / y


print("What calculation would you like to make?")
print("Add")
print("Subtract")
print("Divide")
print("Multiply")


choice = input("Enter choice (add/subtract/divide/multiply)\n")


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))        

if choice == ("add, Add"):
    print(add(num1,num2))

elif choice == ("subtract, Subtract"):
    print(subtract(num1,num2))

elif choice == ("divide, Divide"):
    print(divide(num1,num2))

elif choice == ("multiply, Multiply"):
    print(multiply(num1,num2))`

1 个答案:

答案 0 :(得分:8)

而不是:

choice == ("add, Add")

你想:

choice in ["add", "Add"]

或更有可能:

choice.lower() == "add"

为什么呢?您尝试检查选择输入是否等于代码中的元组(" add,Add"),这不是您想要的。您想要检查选择输入是否在列表中["添加","添加"]。或者,处理此输入的更好方法是将输入小写并将其与所需的字符串进行比较。

相关问题