weixin_39836533
weixin_39836533
2017-09-04 09:37
采纳率: 100%
浏览 2.2k

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
    Lucky_girl42 2017-09-07 03: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时会直接跳出循环,就不会报错了。

    点赞 评论
  • weixin_39836533
    weixin_39836533 2017-09-04 09: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)

    点赞 评论
  • oyljerry
    oyljerry 2017-09-05 12:41

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

    点赞 评论
  • weixin_39836533
    weixin_39836533 2017-09-07 16:43

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

    点赞 评论

相关推荐