[Tutor] Please Help

Sven svenito at gmail.com
Thu Mar 21 11:58:56 CET 2013


Please trim unrelated text from emails.

On 21 March 2013 10:42, Arijit Ukil <arijit.ukil at tcs.com> wrote:

> I am new to python. I like to calculate average of the numbers by reading
> the file 'digi_2.txt'. I have written the following code:
>
> def average(s): return sum(s) * 1.0 / len(s)
>
> f = open ("digi_2.txt", "r+")
>
> list_of_lists1 = f.readlines()
>
>
> for index in range(len(list_of_lists1)):
>
>
>     tt = list_of_lists1[index]
>
>     print 'Current value :', tt
>
> avg =average (tt)
>
>
> This gives an error:
>
> def average(s): return sum(s) * 1.0 / len(s)
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>

tt is a string as it's read from the file. int(tt) would fix the problem.
But in addition you're also not actually calculating the average.


def average(s):
    return sum(s) / len(s)


# convert the list of strings to a list of floats
tt = [float(x) for x in list_of_lists1]

avg = average(tt)

 --
./Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130321/5afcc062/attachment-0001.html>


More information about the Tutor mailing list