0

I am trying to get the average and total from a txt file through an array. I got the txt file to display but for some reason i am having trouble converting the string to int. I can get the line value to convert to int but not the number array. i keep getting errors saying argument must be a string or number not list. The way i have my code set up no is it just keeps adding the first number but not the next numbers after that. I'm fairly new to programming and this program seems so simply but i cant figure this part out. any help will be greatly appreciated.

user3496031
  • 3
  • 1
  • 1
  • 4
  • We probably need to see some lines from numbers.dat. – jgritty Apr 04 '14 at 00:48
  • `lines` and `line` are different variables. Try `total= total + int(line)` – ssm Apr 04 '14 at 00:51
  • numbers.dat is a file that has the following numbers: 40,2,-33,323,80,98 I'm just trying to add them all up and i think i need to make the number = [] into a int but i keep getting an error msg every time i try. i tried total + int(line) and it says ValueError: invalid literal for int() with base 10: – user3496031 Apr 04 '14 at 00:53
  • If you are new to Python, its easier to do: `with open(fileName) as f: total = sum( map(int, f.readlines()) )` or something similar. Also try to learn abour iterators and how to use them like: `for line in open(fileName): ...` – ssm Apr 04 '14 at 00:56

2 Answers2

0

There is a lot of improvement in your code. You could even do this in one line, but I think this will be more clear:

total = 0.0
counter = 0
for line in open('numbers.dat', 'r'):
    total += int(line)
    counter += 1
print 'Total', total
print 'Average', total/counter

So, since a file is iterable you can iterate it with for in. The rest of code is obvious.

Marcos
  • 4,643
  • 7
  • 33
  • 60
  • Thanks that worked. You have any suggestions on where I can go to learn more about python. I tried tutorial videos on youtube but i feel like all they do is teach the very basics of it. the class i take only cover concepts of programming and not python specifically. thanks again – user3496031 Apr 04 '14 at 01:38
  • You are welcome. About Python, check this out: http://stackoverflow.com/questions/2573135/python-progression-path-from-apprentice-to-guru – Marcos Apr 04 '14 at 22:44
0

I think enrmarc's on the right track, but the code could be even more Pythonic by using the with statement and enumerate to count the items.

with open("numbers.dat") as f:
    total = 0

    for counter, line in enumerate(f):
        total += int(line)

    counter += 1
    print "Total", counter
    print "Average", float(total) / counter
Dan Loewenherz
  • 10,879
  • 7
  • 50
  • 81