【发布时间】:2016-09-06 00:26:35
【问题描述】:
我正在编写一个程序,我正在对存储在文件中的数字进行简单的计算。但是,它继续返回 ValueError。我应该在代码中更改什么或如何编写文本文件?
文件是:
def main():
number = 0
total = 0.0
highest = 0
lowest = 0
try:
in_file = open("donations.txt", "r")
for line in in_file:
donation = float(line)
if donation > highest:
highest = donation
if donation < lowest:
lowest = donation
number += 1
total += donation
average = total / number
in_file.close()
print "The highest amount is $%.2f" %highest
print "The lowest amount is $%.2f" %lowest
print "The total donation is $%.2f" %total
print "The average is $%.2f" %average
except IOError:
print "No such file"
except ValueError:
print "Non-numeric data found in the file."
except:
print "An error occurred."
main()
它正在读取的文本文件是
John Brown
12.54
Agatha Christie
25.61
Rose White
15.90
John Thomas
4.51
Paul Martin
20.23
【问题讨论】:
-
当它读入“John Brown”行时会发生什么?似乎您没有跳过所有其他行,这只是一个名称。但它第一次定义的最高值在哪里?
标签: python python-2.7