[Python] Traceback (Most recent call last) error in python

Discussão em 'Python' iniciado por Stack, Junho 26, 2025.

  1. Stack

    Stack Membro Participativo

    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)


    I am trying to implement binary adder for 4 bits. I get the following error. What's the problem with line 22 ? I don't understand why there is an out of range error.

    Error:

    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

    Continue reading...

Compartilhe esta Página