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

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条回答 默认 最新

  • 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时会直接跳出循环,就不会报错了。

    评论
    解决 无用
    打赏 举报
  • 查看更多回答(3条)

相关推荐 更多相似问题