我想知道当我想显示我的文件时如何计数,但不想把计数加到我的平均成绩中
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()
为什么每次循环都要打印平均值?在循环完成之前,你不可能知道平均值是多少。此外,最好是除以文件中的实际分数,而不是假设为29。请尝试以下方法:
相关问题 更多 >
编程相关推荐