在为我的朋友编写二进制转换程序时,我在使用X[N] = Y
命令时不断收到索引超出范围错误X
是一个列表,N
索引号是列表(由一个名为的变量表示Bit
)并且Y
是我分配给变量的值N
在列表中的索引中X
。
好吧,我应该只是放代码并进行解释,但基本上它是说索引超出范围,而代码Numbers[Bit] = 0
或Number[Bit] = 1
在 while 循环内,但是它在代码中的其他任何地方都有效。变量Bit
等于整数 7,列表Numbers
包含变量a
, b
, c
, d
, e
, f
,g
和h
所有分隔的意思是有 0-7 个索引。我尝试使用Bit
0 值,但这也不起作用。但是,只要将Numbers[Bit]
代码部分放在 while 循环之外,代码就可以正常工作。有任何想法吗?
a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
g = 0
h = 0
def loop():
Bit = 7
Numbers = [a, b, c, d, e, f, g, h];
Num = 128
Input = int(input("What Number do you want to convert?" ))
while Input > 0:
if Input > Num:
Input = Input - Num
Numbers[Bit] = 1
else:
Numbers[Bit] = 0
Bit = Bit - 1
Num = Num/2
Numbers = str(Numbers)
print (Numbers)
loop()