我怎样才能从平均成绩中排除我的计数呢?

2024-04-26 02:18:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道当我想显示我的文件时如何计数,但不想把计数加到我的平均成绩中

def main():
    choice = "q"
    while choice != "X":
        print_menu()
        choice = input("Enter an option (D, C, X): ")
        if choice == "D":
            DisplayScores()
        elif choice == "C":
            CalcAverage()

def print_menu():
    print("D. Display Grades")
    print("C. Calculate Average")
    print("X. Exit Application")

def DisplayScores():
    try:
        infile = open("data.txt",'r')
        count = 0
        for line in infile:
            count += 1
            print(count,line.rstrip("\n"))
            line = infile.readline() 
        infile.close()
    except IOError:
        print("File does not exist.")
    except:
        print("Unknown error.")

def CalcAverage():
    Average = 0.0
    try:
        datafile = open("data.txt", 'r')
        for grade in datafile:
            total = float(grade)
            Average += total
            print("The average of the class is: ", format(Average/29, '.2f'))
    except IOError:
        print("Something is wrong with the file.")
        print("Unknown Error.")
    datafile.close()

main()

Tags: maindefcountlineinfilemenu计数print
1条回答
网友
1楼 · 发布于 2024-04-26 02:18:05

为什么每次循环都要打印平均值?在循环完成之前,你不可能知道平均值是多少。此外,最好是除以文件中的实际分数,而不是假设为29。请尝试以下方法:

total = 0.0
grades = 0
try:
    datafile = open("data.txt", 'r')
    for grade in datafile:
        grades += 1
        total += float(grade)
    print("The average of the class is: ", format(total/grades, '.2f'))

相关问题 更多 >