[Tutor] Hello again. and another question.
Alan Gauld
alan.gauld at btinternet.com
Fri Oct 3 02:16:43 CEST 2008
<tsmundahl at comcast.net> wrote
> I got the files to read and print out the grades and averages,
> but when I write these files to the other txt file, all that I get
> is:
>
> 10.0
> 10.0...
> I know it is something simple. I am just not seeing it.
When the output doesn't vary like this you know you must be
writing the wrong value or the same value multiple times.
I'll add several comments on the code but the solution
is in there too...
Grades = [ ]
filename = raw_input("Enter the filename with 10 grades to be
averaged: ")
my_file_object = open (filename, "r")
for a in range (10):
temp_string = my_file_object.readline()
Grades = Grades + [ float (temp_string)]
my_file_object.close()
for a in range (len(Grades)):
print "Grade", str (a + 1) + ":", Grades [a]
##########
# It would be better to just iterate over Grades:
for index, grade in enumerate(Grades):
print "Grade", index,":",grade
total = 0
for a in range (len(Grades)):
total = total + Grades[a]
######
# same here:
for grade in Grades:
total += grade
average = total/float (len(Grades))
######
# you don't need the float conversion here
because you converted them all to floats
at the beginning.
print "The average grade was: ", round(average,2)
print ""
print "Okay, we are assuming that you have created a file named
'grade_file_2.txt' that is empty, yes?"
print ""
fname= raw_input("Please enter 'grade_file_2.txt' to write to new
file: ")
grades_file_2 = open("grade_file_2.txt", "w")
for count in range (len(Grades)):
grades_file_2.write(str("%.2f"% (len(Grades))) + "\n")
#####
# Notice you are writing len(Grades) which is always 10 - your error!
But...
#####
# and again the for loop, and simplify the output string:
for grade in Grades:
grades_file_2.write("%.2f\n" % grade)
grades_file_2.close()
////////////////////////////
Python for loops are much more powerful when used
as foreach loops rather than always using indexing.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list