[Tutor] reading strings and calculating totals
ALAN GAULD
alan.gauld at btinternet.com
Sat Aug 30 23:17:14 CEST 2014
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?
You can find out by inserting a print line:
with open('/Users/richarddillon/Desktop/numbers.txt', 'r') as infile:
for line in infile:
print('Line = ', line)
total += float(line)
And see what the offending line looks like.
Once you know what the error is caused by you can add a line
or two to avoid (or handle) the problematic cases.
Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140830/9927d66c/attachment.html>
More information about the Tutor
mailing list