简体   繁体   English

Python 计算文件中数字的平均值 (Pearson Revel)

[英]Python calculating average of numbers in a file (Pearson Revel)

I am working on a homework question, and I don't understand how to solve it.我正在做一个家庭作业问题,我不明白如何解决它。 The question is:问题是:

Assume that a file containing a series of integers is named numbers.txt.假设包含一系列整数的文件名为 numbers.txt。 Write a program that calculates the average of all the numbers stored in the file.编写一个程序来计算存储在文件中的所有数字的平均值。

I tried:我试过了:

def main():
    try: 
        numbersFile = open ("numbers.txt","r")
    except IOError as errorGenerated: 
        print("File not found:",errorGenerated)
    else: 
        total = 0
        numberOfLines = 0
        line = numbersFile.readline()
        
        while line != "":
            numberOfLines += 1
            total += int(line)
            line = numbersFile.readline()
            
        average = total/numberOfLines
main()

Any help would be greatly appreciated!任何帮助将不胜感激!

*I fix my typo, but there is still a logic error *我修正了我的错字,但仍然存在逻辑错误

You spelled "numberOfLines" wrong in your else statement LOL:你在else语句中拼错了“numberOfLines”,哈哈:

def main():
    try: 
        numbersFile = open ("numbers.txt","r")
    except IOError as errorGenerated: 
        print("File not found:",errorGenerated)
    else: 
        total = 0
        numberOfLines = 0 #here
        line = numbersFile.readline()
        
        while line != "":
            numberOfLines += 1
            total += int(line)
            line = numbersFile.readline()
            
        average = total/numberOfLines  
        #make sure you print the output!
        print(average)

main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM