python中的Traceback(最近调用last)错误

时间:2014-09-26 23:52:12

标签: python traceback

def adder(l1,l2,op):

    if(op == 0):

        carry = 0
        result = []
        l1.reverse()
        l2.reverse()

        for x in range(0, 4):

            sum = l1[x] + l2[x] + carry

            if(sum == 0):
                result[x] = 0
                carry = 0
            elif(sum == 1):
                result[x] = 1
                carry = 0
            elif(sum == 2):
                result[x] = 0
                carry = 1
            elif(sum == 3):
                result[x] = 1
                carry = 1

            if(x == 2):
                carry_in = carry
            if(x == 3):
                carry_out = carry

    result.reverse()

    overflow = carry_in ^ carry_out
    sign = result[3]
    zero = not(result[0] | result[1] | result[2] | result[3]) 
    sign_of_true_result = overflow ^ sign

    print result,carry,overflow,sign,zero,sign_of_true_result


number1 = []
number2 = []
print "Enter the bits of number 1 one by one: "

x = 0
while(x < 4):

    digit_1 = raw_input()

    if(digit_1 != '0' and digit_1 != '1'):
        print "Please enter either 0 or 1"
        continue
    else:
        x = x + 1
        number1.append(int(digit_1))

print "Enter the bits of number 2 one by one: "

y = 0       
while(y < 4):

    digit_2 = raw_input()

    if(digit_2 != '0' and digit_2 != '1'):
        print "Please enter either 0 or 1"
        continue
    else:
        y = y + 1
        number2.append(int(digit_2))

op = int(raw_input("Press 0 for addition or 1 for substraction (Op): "))

if __name__ == '__main__':
    adder(number1,number2,op)

我正在尝试为4位实现二进制加法器。我收到以下错误。第22行有什么问题?我不明白为什么会出现超出范围的错误。

错误:

Traceback (most recent call last):
  File "ex9.py", line 85, in <module>
    adder(number1,number2,op)
  File "ex9.py", line 22, in adder
    result[x] = 0
IndexError: list assignment index out of range

1 个答案:

答案 0 :(得分:1)

你从这开始:

result = []

所以result没有价值。

第一次循环,x0,您尝试将result[0]重新分配给01。但 没有result[0]。所以你得到IndexError

你可以在一个更简单的例子中看到同样的事情:

>>> result = []
>>> result[0] = 0
IndexError: list assignment index out of range

您需要重新组织代码,以便在获得位时附加或添加位,或者需要使用例如result[None, None, None, None]预先填充[0, 0, 0, 0]或其他东西,以便result[0]有意义。


  

我对第85行发生的第一个错误更感兴趣。

你在第85行确实没有错误。请注意,追溯显示“最近一次呼叫最后一次”:

Traceback (most recent call last):
  File "ex9.py", line 85, in <module>
    adder(number1,number2,op)
  File "ex9.py", line 22, in adder
    result[x] = 0
IndexError: list assignment index out of range

result[x] = 0第22行的adder提出IndexError,因为x0result为空。

位于模块顶层的第85行的adder(number1,number2,op)引发IndexError,因为它调用了一个引发IndexError并且没有{{1}的函数围绕该调用的/ try:(或except IndexError:的某些超类)。

并且,因为那是在顶级,所以代码中没有更高的位置可以处理它,因此解释器通过打印回溯并退出来处理它。