猿问

python 文件循环

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=count+1

        line=infile.readline()

    print ("\nThe average of the numbers is")

main()


What file are the numbers in? C:\Users\john\Documents\ze.txt

Traceback (most recent call last):

  File "C:/Users/john/AppData/Local/Programs/Python/Python36-32/s.py", line 12, in <module>

    main()

  File "C:/Users/john/AppData/Local/Programs/Python/Python36-32/s.py", line 8, in main

    sum=sum+eval(line)

  File "<string>", line 1

    

    ^

SyntaxError: unexpected EOF while parsing

哪里出错了?是sum哪里吗,为什么错了?


宝慕林9499331
浏览 1426回答 1
1回答

慕仔3118017

   while line != " ": 改成while line:就可以了,当读到eof时line为None。而不是空格
随时随地看视频慕课网APP
我要回答