2 weixin 39836533 weixin_39836533 于 2017.09.04 17:37 提问

python一个关于while循环的报错问题

girls = ['gujin','yangmi','zhengshuang']
my_girls = []
a = len(girls)
a = int(a)
while a >= 0:
a=a-1
girl = girls.pop()
my_girls.append(girl)
continue
for my_girl in my_girls:
print(my_girl)

报错:
Traceback (most recent call last):

File "girls4.py", line 6, in
girl = girls.pop()
IndexError: pop from empty list

这段执行不报错:
girls = ['gujin','yangmi','zhengshuang']
my_girls = []
while girls:
girl = girls.pop()
my_girls.append(girl)
for my_girl in my_girls:
print(my_girl)

4个回答

WLY19930402
WLY19930402   2017.09.07 11:14
已采纳

执行循环语句时,当a=1,判断a>=0满足,执行a=a-1,此时a=0,继续判断,a>=0仍然满足,执行a=a-1,此时a=-1,执行girl = girls.pop()必然出错,因为索引下标从 0 开始,所以直接把 while a >= 0 改成 while a > 0,这样当a=0时会直接跳出循环,就不会报错了。

oyljerry
oyljerry   Ds   Rxr 2017.09.05 20:41

while判断不要等号。while a > 0:

weixin_39836533
weixin_39836533   2017.09.04 17:53

girls = ['gujin','yangmi','zhengshuang']
my_girls = []
a = len(girls)
a = int(a)
while a >= 0:
a=a-1
if a >= 0:
girl = girls.pop()
my_girls.append(girl)
else:
break

for my_girl in my_girls:
print(my_girl)

weixin_39836533
weixin_39836533   2017.09.08 00:43

我自己是这么理解的,a是我定义的变量 按照我原来的写法,a分别为3,2,1,0,while要执行4次
但是我的girls列表,只满足执行3次就是空列表,取无可取

Csdn user default icon
上传中...
上传图片
插入图片