[Tutor] reading strings and calculating totals

Peter Otten __peter__ at web.de
Sat Aug 30 22:07:26 CEST 2014


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
>     infile = open('/Users/richarddillon/Desktop/numbers.txt', 'r')
>     # read first record
>     line = infile.readline()
>     a = float(line)
>     # read rest of records
>     while line != '':
>         total = total + a
>         line = infile.readline()
>     infile.close()
>     print(total)
> 
> main()

Hint: look at the while loop. You never set `a` to a new value, you just 
keep adding the value found in the first line.

PS: Once you have fixed this try rewriting your code with a for loop

...
for line in infile:
   ...

This is the idiomatic way in Python and will also simplify your code.



More information about the Tutor mailing list