Python:类型错误

时间:2014-11-11 03:37:28

标签: python-3.4

所以这是我的情况。我一直在尝试在python 3.4中创建一个高级计算器,你可以在其中键入这样的东西。 ' 1 + 1'然后它会给你答案' 2'。现在我将解释我的计算器应该如何工作。因此,您首先输入数学方程式,然后根据空格计算您输入的单词。它这样做是因为它知道未来的循环需要多长时间。然后它会分割你输入的所有内容。它将它分成了str和int,但它们仍然在同一个变量中,它们仍然按顺序排列。我遇到麻烦的事情就是要实际进行计算。

这是我的所有代码 -

    # This is the part were they enter the maths equation
    print("-------------------------")
    print("Enter the maths equation")
    user_input = input("Equation: ")
    # This is were it counts all of the words
    data_count = user_input.split(" ")
    count = data_count.__len__()
    # Here is were is splits it into str's and int's
    n1 = 0
    data = []
    if n1 <= count:
        for x in user_input.split():
            try:
                data.append(int(x))
            except ValueError:
                data.append(x)
            n1 += 1
    # And this is were it actually calculates everything
    number1 = 0
    number2 = 0
    n1 = 0
    x = 0
    answer = 0
    while n1 <= count:
        #The code below checks if it is a number
        if data[n1] < 0 or data[n1] > 0:
            if x == 0:
                number1 = data[n1]
            elif x == 1:
                number2 = data[n1]
        elif data[n1] is "+":
            if x == 0:
                answer += number1
            elif x == 1:
                answer += number2
        n1 += 1
        x += 1
        if x > 1:
            x = 0
    print("Answer =", answer)

但在计算过程中它会混乱并给我错误

错误 -

    if data[n1] < 0 or data[n1] > 0:
    TypeError: unorderable types: str() < int()

谁能看到我在这里做错了什么? 感谢

1 个答案:

答案 0 :(得分:1)

当您比较字符串和整数时,会出现此问题。 Python不猜,它会引发错误。 要解决此问题,只需调用int()将字符串转换为整数:

int(input(...))

因此,更正后的陈述应为:

if int(data[n1]) < 0 or int(data[n1]) > 0: