[Tutor] reading strings and calculating totals

Alex Kleider akleider at sonic.net
Sun Aug 31 20:32:19 CEST 2014


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()
> 
> 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

..but isn't there a problem if the file contains empty lines?

>>> float("\n")
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: could not convert string to float:
>>> float('')
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: could not convert string to float:
>>> 


More information about the Tutor mailing list