pythonwhile-loopsyntax-errorevalreadline

Using eval() with a variable and getting a syntax error


I am trying to find the average of numbers in a file using a while loop. I'm using readline() to get the numbers from the file and assign them to a variable, and this results in them being read as strings. This is the code:

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()

And this is what happens when I run it:

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

What am I doing wrong?


Solution

  • Here is a better way to organize your code:

    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()