Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help fnding the average of a set of numbers in python

in my data file I have

60,66,88,90,44,90,80,77

all the numbers are in one line

this is my code which does not give me the average of my numbers

    inFile3 = open("data2.txt","r") 
    global gradeVar 
    gradeVar = len(gradeArray) 
    global Total 
    Total = 0 
    for Numbers in inFile3: 
            Total = Total + int(Numbers) 
    inFile3.close() 
    global averageVar 
    averageVar = Total/gradeVar 
    return averageVar 

This is the error

Traceback (most recent call last):
  File "program.py", line 81, in <module>
    main()
  File "program.py", line 5, in main
    averageVar = Average() 
  File "program.py", line 39, in Average
    Total = Total + int(Numbers) 
ValueError: invalid literal for int() with base 10: '60,66,88,90,44,90,80,77\n'
like image 366
Liam Yorkville Avatar asked Dec 21 '22 17:12

Liam Yorkville


2 Answers

Your problem is here:

for Numbers in inFile3: 
        Total = Total + int(Numbers)

Numbers in the code above is a list of lines, rather than a list of numbers.

for Line in inFile3:
    for number in Line.split(','):
        Total = Total + int(number)

should help.

You also have no need to pre-declare variables the way you are in Python. In fact, doing so with global is positively dangerous unless you know what you're doing and why.

Edit: If you ever have a comma at the end of a line, of a blank value you can change the final line to:

        if number.strip():
            Total = Total + int(number)

This will ignore any 'empty' number strings that would otherwise throw an error.

like image 132
mavnn Avatar answered Jan 13 '23 23:01

mavnn


This line:

for Numbers in inFile3:

is actually iterating over the lines of the file, not the numbers within each line. You need to iterate over the lines, then for each line split it into numbers, something like this:

for Line in inFile3: 
    for Number in Line.split(','): 
        Total = Total + int(Number) 
like image 23
RichieHindle Avatar answered Jan 13 '23 22:01

RichieHindle