我正在尝试使用 while 循环查找文件中数字的平均值。 我使用 readline() 从文件中获取数字并将它们分配给变量,这会导致它们被读取为字符串。这是代码:
def main():
fileName = input("What file are the numbers in?")
infile = open(fileName, 'r')
sum = 0.0
count = 0
line = infile.readline()
while line != " ":
sum = sum + eval(line)
count += 1
line = infile.readline()
print("The average of the numbers is", sum/count)
main()
这就是我运行它时发生的情况:
What file are the numbers in?Sentinel_numbers
Traceback (most recent call last):
File "C:\Users\Akua Pipim\PycharmProjects\pythonProject6\Numbers_from_file2.py", line 15, in <module>
main()
File "C:\Users\Akua Pipim\PycharmProjects\pythonProject6\Numbers_from_file2.py", line 8, in main
number = eval(line)
^^^^^^^^^^
File "<string>", line 0
SyntaxError: invalid syntax
我做错了什么?
这是组织代码的更好方法:
def main():
fileName = input("What file are the numbers in?")
infile = open(fileName, 'r')
sum = 0.0
count = 0
for line in infile:
line = line.strip()
if line:
sum = sum + float(line)
count += 1
print("The average of the numbers is", sum/count)
main()