LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Calculating average from Python Script (https://www.linuxquestions.org/questions/programming-9/calculating-average-from-python-script-804128/)

stryker213 04-25-2010 02:15 PM

Calculating average from Python Script
 
Hello, I'm trying to write a python script that will calculate my test scores from a text file named "exams."

Sample input would be:
Calculus 85 90
Physics 90 85 93

Output will look like:
Calculus 87.5
Physics 89.3

I have the following code:
Code:

#!/usr/bin/python
import math
import sys

f = open('exams',"r")
l = f.readline()
while l :
 l = l.split(None,10)
 L = l[1:]
 print sum
 print l[:1]
 print 'Scores ', L
 print 'Number of Values ', len(L)
 l = f.readline()

My intent is to sum the values found in L and divide by len(L).

I think my issue is that when I split the values, I get a string array (ex. ['85', '90'] ), which makes it hard to do calculations.

indienick 04-25-2010 02:29 PM

You can convert strings to integers in Python by passing the value to the int() function, like so:
Code:

>>> int('230498')
230498
>>>


Mara 04-25-2010 02:33 PM

print int(L[0])

The int operator gives you the conversion you need.

stryker213 04-25-2010 02:35 PM

Quote:

Originally Posted by indienick (Post 3947325)
You can convert strings to integers in Python by passing the value to the int() function, like so:
Code:

>>> int('230498')
230498
>>>


Thanks for the advice indienick. However, it's still not working. My code takes each line of text and parses it into a array so that it looks like this: ['Calculus', '85', '90']. Using L = l[1:], gives me ['85', '90'], which is close. If I used your method (L = int(l[1:])), I get an error.

stryker213 04-25-2010 02:38 PM

Quote:

Originally Posted by Mara (Post 3947327)
print int(L[0])

The int operator gives you the conversion you need.

Mara, thank you very much for your help. Your method does work for individual iterations, but how can I make it so that it goes through my entire exam list? For example, I may have two test scores for one subject and four in another.

Thanks again!

indienick 04-25-2010 04:58 PM

Maybe try something like this:
Code:

average = 0

for x in range(1, len(l)):
  score = int(l[x])
  average += score

average = float(average / (len(l) - 1))
print average



All times are GMT -5. The time now is 05:57 PM.