[Tutor] reading strings and calculating totals

Alan Gauld alan.gauld at btinternet.com
Sat Aug 30 22:13:03 CEST 2014


On 30/08/14 17:14, Richard Dillon wrote:

> The total I get doesn't match the values entered in the file.
>
> def main():
>      total = 0
>      infile = open('/Users/richarddillon/Desktop/numbers.txt', 'r')
>      # read first record
>      line = infile.readline()
>      a = float(line)

Here you get the number a

>      # read rest of records
>      while line != '':
>          total = total + a

And here you add a (calculated above) to total.

>          line = infile.readline()

And here you end the loop so you effectively add a to
total for as many lines as are in the file.
You effectively calculate

a * (len of file-1)

You need to convert line to float and add that to total
inside the loop.

BUT, there is a much better way using Pythons for loop:

total = 0
for line in infile:
     total += float(line)

That automatically reads all the lines ion the file so
you don't need to check for empty lines, set up the
first line etc.

>      infile.close()

And if you use Pythons 'with' structure you don't
need the close either, so your whole becomes

total = 0
with open('/Users/richarddillon/Desktop/numbers.txt', 'r') as infile:
     for line in infile:
         total += float(line)
print(total)

Which is shorter, safer, and more readable.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list