Python basic计算器程序不支持';不回答
因此,我试图找出如何用我在python中学到的东西制作计算器,但我就是不能让它给我一个答案 这是我目前掌握的代码:Python basic计算器程序不支持';不回答,python,calculator,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
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))`
而不是:
choice == ("add, Add")
你想要:
choice in ["add", "Add"]
或者更可能:
choice.lower() == "add"
为什么??您试图检查选项输入是否等于代码中的元组(“add,add”),这不是您想要的。而是要检查选项输入是否在列表[“添加”、“添加”]中。或者,处理此输入的更好方法是将输入小写,并将其与所需字符串进行比较 为了帮助捕获这样的bug,请尝试在if/elif块的末尾添加一个“else”块-然后您可以看到,如果您到达“else”,它与您的任何选择都不匹配。我在末尾有一个else,但我删除了它,因为它一直在运行,因此这意味着它上面的代码没有被选中,因此出现了问题?是的,这就是它的意思。删除else只意味着你看不到它跳过其他选项,这不会改变它们是否匹配。啊,所以我的方式是你必须键入add,add而不是其中任何一个!?多谢各位