将 eval() 与变量一起使用并出现语法错误

问题描述 投票:0回答:1

我正在尝试使用 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

我做错了什么?

python while-loop syntax-error eval readline
1个回答
0
投票

这是组织代码的更好方法:

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()
© www.soinside.com 2019 - 2024. All rights reserved.