あなたは分裂しています b1
単一のスペースで、これは空の値につながる可能性があります:
>>> '88 89 '.split(' ')
['88', '', '89', '']
ここにある余分な空の文字列が原因です int()
例外をスローするには:
>>> int('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
使用する str.split()
と 番号 代わりに議論;その後、余分な空白が剥がれます:
>>> '88 89 '.split()
['88', '89']
コードには他にもいくつかの問題があります。よく見てください:
def lab8():
userinput= "Lab8.txt"
lenoffile= len(userinput)
print "There is", lenoffile, "lines"
File= open (userinput, "r")
studentscores1= File.read()
studentlist= studentscores1.split("\n")
return studentlist, lenoffile
ここ、 lenoffile
は いいえ ファイル内の行の数。の文字の数です 'Lab8.txt'
;両方の値 起こる することが 8
, 、しかし、そのファイルからいくつかの行を追加または削除すると、コードの残りの部分が間違っています。
これらの数字を名前と一緒に保持し、もう一度計算を書き留めることになっている場合は、いくつかの作業を行う必要があります 維持 一緒に名前。
同じタスクを解決するための代替バージョンは次のとおりです。
outputfile = raw_input("What is the output filename? :")
with open('Lab8.txt') as infile, open(outputfile, 'w') as outtfile:
for name in infile:
scores = next(infile).split() # next() grabs the next line from infile here
scores = map(int, scores)
quiztotal = sum(scores[:4]) / 5
midtermtotal = sum(scores[5:7]) / 2
finaltotal = scores[7]
score = quiztotal * .3 + midtermtotal * .4 + finaltotal * .3
outfile.write(name)
outfile.write('{0:0.2f}\n'.format(score))