Re: [Tutor] reading strings and calculating totals

2014-08-31 Thread Alan Gauld
On 31/08/14 19:32, Alex Kleider wrote: total = 0 with open('/Users/richarddillon/Desktop/numbers.txt', 'r') as infile: for line in infile: total += float(line) print(total) ..but isn't there a problem if the file contains empty lines? Yes you are right. And my second reply did po

Re: [Tutor] reading strings and calculating totals

2014-08-31 Thread Alex Kleider
On 2014-08-30 13:13, Alan Gauld wrote: 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()

Re: [Tutor] reading strings and calculating totals

2014-08-30 Thread ALAN GAULD
total = 0 >with open('/Users/richarddillon/Desktop/numbers.txt', 'r') as infile: >   for line in infile: >       total += float(line) >print(total) > > >Python returned         "ValueError: could not convert string to float: " > >That means some of your lines are not floats - are there any blanks?

Re: [Tutor] reading strings and calculating totals

2014-08-30 Thread Richard Dillon
When I tried total = 0 with open('/Users/richarddillon/Desktop/numbers.txt', 'r') as infile: for line in infile: total += float(line) print(total) Python returned "ValueError: could not convert string to float: " Richard On Aug 30, 2014, at 1:13 PM, Alan Gauld wrote: > total

Re: [Tutor] reading strings and calculating totals

2014-08-30 Thread Alan Gauld
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 nu

Re: [Tutor] reading strings and calculating totals

2014-08-30 Thread Peter Otten
Richard Dillon wrote: > I apologize in advance - This is my third week using Python (3.4.1 on a > Mac) > > I need to read a text file, convert the values into numbers and calculate > a total. The total I get doesn't match the values entered in the file. > > def main(): > total = 0 > infi

[Tutor] reading strings and calculating totals

2014-08-30 Thread Richard Dillon
I apologize in advance - This is my third week using Python (3.4.1 on a Mac) I need to read a text file, convert the values into numbers and calculate a total. The total I get doesn't match the values entered in the file. def main(): total = 0 infile = open('/Users/richarddillon/Desktop/