为什么我的简单python计算器在分割时给出2个答案(1个正确,1个错误)?

时间:2015-02-23 15:46:45

标签: python calculator

为学校做这个,我决定做一个计算器。这段代码工作正常,除了分给我2个答案?

编辑:一旦我添加了选项,也可以输入" sub",似乎正在减去。我删除了该选项并修复了它。

#Numbers/Answer to Add
print("If your not Adam, welcome to The Calculator\n")
firstNumb = float(input("A number\n"))
secondNumb = float(input("Another number\n"))
operation = input("mutliply/divide/subtract/add?\n")

#Operating

answerMult = firstNumb * secondNumb
answerDiv = firstNumb / secondNumb
answerAdd = firstNumb + secondNumb
answerSub = firstNumb - secondNumb

#Printing answers

if(operation == "multiply"):
    print(answerMult)

if(operation == "divide"):
    print(answerDiv)

if(operation == "add"):
    print(answerAdd)

if(operation == "subtract","sub"):
    print(answerSub)


#EasterEgg

if((answerAdd) == 9001):
    while(1==1):print("ITS OVAR 9000!!!!!!\n")

if((answerSub) == 9001):
    while(1==1):print("ITS OVAR 9000!!!!!!\n")

if((answerMult) == 9001):
    while(1==1):print("ITS OVAR 9000!!!!!!\n")

if((answerDiv) == 9001):
    while(1==1):print("ITS OVAR 9000!!!!!!\n")

3 个答案:

答案 0 :(得分:4)

问题在于以下几点:

if(operation == "subtract","sub"):
    print(answerSub)

(operation == "subtract, "sub")会创建一个元组,如(False, "sub"),并且始终为True

您对==行为感到困惑,您可以使用if operation in ["subtract", "sub"]:

关于Python的一个小建议,如果声明条件是不必要的并且可能导致一些错误的括号。你可以省略括号。

答案 1 :(得分:0)

问题出在你的分歧上:

if(operation == "subtract","sub"):

这应该是

if (operation == "subtract") or (operation == "sub"):

if operation in ["subtract", "sub"]:

答案 2 :(得分:0)

这是utdemir所说的。删除“sub”部分会给出正确的解决方案

print("If your not Adam, welcome to The Calculator\n")
firstNumb = float(input("A number\n"))
secondNumb = float(input("Another number\n"))
operation = input("mutliply/divide/subtract/add?\n")

#Operating

answerMult = firstNumb * secondNumb
answerDiv = firstNumb / secondNumb
answerAdd = firstNumb + secondNumb
answerSub = firstNumb - secondNumb

#Printing answers

if(operation == "multiply"):
    print(answerMult)

if(operation == "divide"):
    print(answerDiv)

if(operation == "add"):
    print(answerAdd)

if(operation == "subtract"):
    print(answerSub)


#EasterEgg

if((answerAdd) == 9001):
    while(1==1):print("ITS OVAR 9000!!!!!!\n")

if((answerSub) == 9001):
    while(1==1):print("ITS OVAR 9000!!!!!!\n")

if((answerMult) == 9001):
    while(1==1):print("ITS OVAR 9000!!!!!!\n")

if((answerDiv) == 9001):
    while(1==1):print("ITS OVAR 9000!!!!!!\n")