Python代码无法正常工作

时间:2014-03-23 02:18:14

标签: python python-2.7 python-3.x

嗨,这是我在这段代码上的第二篇文章我没有得到错误但是if else语句不能正常工作我想要if(calculate [2] == opperations: 代码不起作用,即使我有 - 或+那里它也不会注册。有什么想法吗?它给了我回复抱歉无效的text3。

calculate = input("Enter the problem in the format x + y = z ")

opperations = ["+", "-", "*", "/"]
numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
space = " "
a = calculate[0]
a = int(a)
b = calculate[4]
b = int(b)

def opperation():
if opperations == "+":
    A = 1
elif opperations == "-":
    A = 2
elif opperations == "*":
    A = 3
elif opperations == "/":
    A = 4

if calculate[0] in numbers:
    if len(calculate) > 1:
        if calculate[2] == opperations:
            if calculate[1] == space:
                if A == 1:
                    c = a + b
                    print (c)
                elif A == 2:
                    c = a - b
                    print (c)
                elif A == 3:
                    c = a * b
                    print(c)
                elif A == 4:
                    c = a / b
                    print(c)
                else:
                    print("Sorry invalid text5")
            else:
                print("Sorry invalid text4")
        else:
            print("Sorry invalid text3")
    else:
        print("Sorry invalid text2")
else:
    print("Sorry invalid text1") 

2 个答案:

答案 0 :(得分:2)

条件

if calculate[2] == opperations:

会将calculate[2]与整个列表["+", "-", "*", "/"]进行比较。您可以使用in关键字来检查元素是否在序列中:

if calculate[2] in opperations:
    # ...

,在您将opperations"+"进行比较的部分,"- ...您应该将它们与calculate[2]进行比较:

if calculate[2] == "+":
    A = 1
elif calculate[2] == "-":
    A = 2
elif calculate[2] == "*":
    A = 3
elif calculate[2] == "/":
    A = 4

注意:您的方法只会处理1个数字的操作。我建议你使用split(" ")方法,这样就可以使用它:

s = "100 + 20"
parts = s.split(" ")   # split by space
parts[0] # 100
parts[1] # +
parts[2] # 20

答案 1 :(得分:0)

除了Christian的建议之外,if elif链可以替换为字典查找。在此示例中,lambda a, b: a+b是一个函数,它接受两个值ab并返回sum。这意味着opperations["+"]会返回一个函数,opperations["+"](a,b)会返回ab之和。

opperations = { "+": lambda a, b: a+b, 
               "-": lambda a, b: a-b,
               "*": lambda a, b: a*b,
               "/": lambda a, b: a/b }

calculate = raw_input("Enter the problem in the format x + y = z ")

numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
space = " "
a = calculate[0]
a = int(a)
b = calculate[4]
b = int(b)

if calculate[0] in numbers:
    if len(calculate) > 1:
        if calculate[2] in opperations:
            if calculate[1] == space:
                c = opperations[calculate[2]](a,b)
                print (c)
            else:
                print("Sorry invalid text4")
        else:
            print("Sorry invalid text3")
    else:
        print("Sorry invalid text2")
else:
    print("Sorry invalid text1")