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'
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With