[Tutor] Hello again. and another question.

Steve Willoughby steve at alchemy.com
Thu Oct 2 23:58:03 CEST 2008

You're doing a good job getting started with
programming here, keep getting the fundamentals
and then learn to refine those concepts over time.

But for future reference, here are some finer 
points for you to keep in mind to improve your
style and get a more Pythonic approach:

On Thu, Oct 02, 2008 at 09:41:37PM +0000, tsmundahl at comcast.net wrote:
> Grades = [ ]

Usually we capitalize class and module names, but not
variables and functions/methods.  

> for a in range (10):
>     temp_string = my_file_object.readline()
>     Grades = Grades + [ float (temp_string)]

Might be more clear here to say


instead of constructing a new list just to use +

You might also want to just read each line in the file
right in the for loop, which allows you to take ANY 
number of lines, not just 10, and makes the code
more concise at the same time:

    for grade in my_file_object:

> for a in range (len(Grades)):
>     print "Grade", str (a + 1) + ":", Grades [a]

If all you're going to do is to deal with each element
of a list in turn, instead of using an index over the
range of the number of elements, just directly iterate
over the list:

    for a in Grades:
       print "Grade:", a

And one GREAT habit to get into is to always be checking
if Python's built in functions and standard library already
offer something you're doing manually:

> total = 0
> for a in range (len(Grades)):
>     total = total + Grades[a]
> average = total/float (len(Grades))

     average = sum(Grades) / len(Grades)

> fname= raw_input("Please enter 'grade_file_2.txt' to write to new file: ")
> grades_file_2 = open("grade_file_2.txt", "w")

I'm not sure why you're asking them to type in a file name
which you're ignoring and opening grade_file_2.txt anyway?

> for count in range (len(Grades)):
>     grades_file_2.write(str("%.2f"% (len(Grades))) + "\n")       
> grades_file_2.close()

No need to explicitly call str() here, and I suspect print would
be clearer anyway.  And again, note the direct iteration over

    for grade in Grades:
        print >>grades_file_2, "%.2f" % grade

Steve Willoughby    |  Using billion-dollar satellites
steve at alchemy.com   |  to hunt for Tupperware.

More information about the Tutor mailing list