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

标签 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))`

最佳答案

代替:

choice == ("add, Add")

你想要:

choice in ["add", "Add"]

或者更有可能:

choice.lower() == "add"

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

关于Python 基本计算器程序不返回答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36972518/

相关文章:

python - 如何通过 Pandas 中的多级索引执行 'groupby'

python - 多线程socket程序-处理临界区

python - 将所有列的信息混合在一个列中

python - 如何过滤蒙版中不需要的点

c# - 只有第一个 if 语句触发

c++ - 我如何获得 '.00' 形式的数字?

java,不使用整数(计算器)

计算器 C : inputting both operator signs and integers to perform calculations

java - 所得税计算器

python - 在 Pandas 中创建日期范围的总和