【发布时间】:2015-12-30 01:35:27
【问题描述】:
在为我的朋友编写二进制转换程序时,我在使用X[N] = Y 命令时不断收到索引超出范围错误,其中X 是一个列表,N 是索引号是列表(由变量名为 Bit) 和 Y 是我分配给列表 X 中索引 N 中的变量的值。
好吧,我应该只输入代码并进行解释,但基本上是说索引超出范围,而代码 Numbers[Bit] = 0 或 Number[Bit] = 1 在 while 循环内,但它在代码中的其他任何地方都有效。变量 Bit 等于整数 7,列表 Numbers 包含变量 a、b、c、d、e、f、g 和 @987654分开的意思是有 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()
【问题讨论】:
-
最初设置为 7。
-
Num/2没有使用整数除法,而是使用真除法。你最终会得到分数,而不是 0。这不是问题的全部,但它没有帮助。
标签: python loops while-loop indexoutofboundsexception python-3.5