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
你从这个开始:
result = []
所以
result
没有值。
第一次循环时,
x
是0
,并且您尝试将result[0]
重新分配给0
或1
。但没有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 行实际上并没有错误。请注意,回溯显示“最近一次调用是最后一次”:
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
第 22 行
result[x] = 0
中的
adder
升高了 IndexError
,因为 x
是 0
并且 result
为空。模块顶层第 85 行的
adder(number1,number2,op)
引发了
IndexError
,因为它调用了引发 IndexError
的函数,并且没有 try:
/except IndexError:
(或某些超类)围绕该通话的 IndexError
)。而且,因为那是在顶层,所以代码中没有更高的地方可以处理它,因此解释器通过打印回溯并退出来处理它。
.py”,第 1 行,位于 从 .Adafruit_CharLCD 导入 * 文件“/home/pi/Desktop/project/workspace/lib/python3.11/site-packages/Adafruit_CharLCD/Adafruit_CharLCD.py”,第 89 行,位于 Adafruit_CharLCD 类(对象): 文件“/home/pi/Desktop/project/workspace/lib/python3.11/site-packages/Adafruit_CharLCD/Adafruit_CharLCD.py”,第 95 行,位于 Adafruit_CharLCD GPIO=GPIO.get_platform_gpio(), ^^^^^^^^^^^^^^^^^^^^^^^^^^ 文件“/home/pi/Desktop/project/workspace/lib/python3.11/site-packages/Adafruit_GPIO/GPIO.py”,第 426 行,位于 get_platform_gpio 中 raise RuntimeError('无法确定平台。') 运行时错误:无法确定平台。