首页 > 解决方案 > 在 List Python 中添加负数

问题描述

遵循python代码有什么问题。

List3=[7,5,4,4,3,1,-2,-3,-5,-7]
total=0
i=6
while i>=6:
    total = total + List3[i]
    i=i+1
    if i> len(List3):
        break
print(total)

while 循环不应该在 List3[6]=-2 处开始添加并在 i 大于列表长度时中断。我的逻辑有什么问题?它返回:

IndexError                                Traceback (most recent call last)
<ipython-input-41-7e2f7eca2eb8> in <module>()
  4 i=6
  5 while 6<= i:
----> 6     totaln = totaln + List3[i]
  7     i=i+1
  8     if i> len(List3):

IndexError: list index out of range

标签: python

解决方案


我认为while循环是错误的。和i = i+1if 条件应该在while循环中。第二点i >= len(List3)是够了。将i > len(List3)导致最后一个索引超出索引范围


推荐阅读