我正在制作一个成绩计算器程序,它将成绩作为字符串,接受该字符串的一部分并将其转换为浮点数,然后将该浮点数添加到变量中。
homework = ['10/10', '8/10', '4/10']
pointsearned = 0.0
def addpts(list):
for grade in list:
global pointsearned
pointsearned = pointsearned + float(list[grade][:list.index('/')])
addpts(homework)
print pointsearned
我收到错误" TypeError:list indices必须是整数,而不是str"
答案 0 :(得分:1)
list[grade]
,但是分数是列表中的元素而不是索引,这就是您收到错误的原因。您还在使用list.index('/')
但是在您的列表中没有元素\
。我改变了代码。检查打击 homework = ['10/10', '8/10', '4/10']
pointsearned = 0.0
def addpts(lst):
for grade in lst:
global pointsearned
pointsearned = pointsearned + float(grade.split('/')[0])
return pointsearned
print addpts(homework)
#print pointsearned