[Tutor] HELP PLEASE
Cameron Simpson
cs at cskk.id.au
Tue Aug 13 06:44:11 EDT 2019
On 12Aug2019 15:11, Marissa Russo <mrusso11 at u.rochester.edu> wrote:
>This is my code:
Thank you.
>This is the output of my updated code:
>Traceback (most recent call last):
> File "/Applications/Python 3.7/exercises .py", line 37, in <module>
> main()
> File "/Applications/Python 3.7/exercises .py", line 33, in main
> m = mean(data[0])
> File "/Applications/Python 3.7/exercises .py", line 29, in mean
> return(sum(nums)/len(nums))
>TypeError: unsupported operand type(s) for +: 'int' and 'str'
Thank you for this as well, it makes things much clearer.
So, to your code:
>import math
Just a remark: you're not using anything from this module. I presume you
intend to later.
>def get_numbers():
> print("This program will compute the mean and standard deviation")
> file1 = input("Please enter the first filename: ")
> file2 = input("Please enter the second filename: ")
> x = open(file1, "r")
> y = open(file2, "r")
> nums = x.readlines()
> nums2 = y.readlines()
As has been mentioned in another reply, readlines() returns a list of
strings, one for each line of text in the file.
In order to treat these as numbers you need to convert them.
> return nums, nums2
>
>def to_ints(strings):
> num_copy = []
> for num in nums:
> num_copy.append(float(num))
> return num_copy
This returns a list of floats. You might want to rename this function to
"to_floats". Just for clarity.
> return to_ints(nums), to_ints(nums2)
This isn't reached. I _think_ you need to put this line at the bottom of
the get_numbers function in order to return two lists of numbers. But it
is down here, not up there.
>def mean(nums):
> _sum = 0
> return(sum(nums)/len(nums))
This is the line raising your exception. The reference to "+" is because
sum() does addition. It starts with 0 and adds the values you give it,
but you're handing it "nums".
Presently "nums" is a list of strings, thus the addition of the initial
0 to a str in the exception message.
If you move your misplaced "return to_ints(nums), to_ints(nums2)"
statement up into the get_numbers function you should be better off,
because then it will return a list of numbers, not strings.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list