Python 2.7 python中的While循环澄清-错误
我有一点python编码的经验,我试着编写一个代码,将列表中除数字99之外的项目相加。这是我的代码:Python 2.7 python中的While循环澄清-错误,python-2.7,loops,while-loop,sum,Python 2.7,Loops,While Loop,Sum,我有一点python编码的经验,我试着编写一个代码,将列表中除数字99之外的项目相加。这是我的代码: grade = [100,30,99,85] i = 0 while grade[i]!=99: i = i + grade[i] print i 但我得到了这个错误: >>> 100 Traceback (most recent call last): File "G:\desktop\test.py", line 3, in <module>
grade = [100,30,99,85]
i = 0
while grade[i]!=99:
i = i + grade[i]
print i
但我得到了这个错误:
>>>
100
Traceback (most recent call last):
File "G:\desktop\test.py", line 3, in <module>
while grade[i]!=99:
IndexError: list index out of range
>>>
>
100
回溯(最近一次呼叫最后一次):
文件“G:\desktop\test.py”,第3行,在
而我呢=99:
索引器:列表索引超出范围
>>>
i
初始化为字母o
,而不是数字0
。(编辑:OP更新了问题)i
设置为等于100
(i+grade[i]
为0+100
)。因此,在第二次迭代中,您试图访问等级的第100个索引,该索引显然不存在,并且正在提升索引器
sum
的简单方法:
grade = [100,30,99,85]
sum_grade = sum(num for num in grade if num != 99)
print(sum_grade)
>> 215
请解释你的第二个问题note@newGIS添加了一个解释。那么,在我的代码中,如何不使用sum函数来实现呢?@newGIS
sum=0;对于等级中的num:;如果num!=99: ; sum+=num
虽然我看不出你为什么要这样做而不是使用sum
。我更喜欢使用while循环