2011-11-20 37 views
0

我寫了幾乎所有的程序,除了我被困在這個特定的部分。我需要寫出一個平均值來將所有學生的最終成績列爲課程的統計數據。學生姓名和最終成績已附加到外部文件(請記住更多學生和成績可以附加)。我需要幫助找到我的Python程序中的算術平均值

這是我到目前爲止,任何輸入是高度讚賞。

fname = input("What is the file name?") 
file1 = open(fname,'r') 
sum = 0.0 
count = 0 
for line in file1: 
    sum = sum + eval(line)          
    count = count + 1 

print("\nThe average of the numbers is", sum/count) 
在第6行( sum = sum + eval(line)

我不斷收到

syntax error: unexpected EOF while parsing (<string>, line 1) 

我不知道有足夠的瞭解Python來知道這意味着什麼。有人可以在代碼中顯示我嗎?並且參考外部文件格式如下:

tom jones,100, 
bill smith,89, 

依此類推。

+0

evaling行是沒有意義的。從行中解析整數。 (或者,如果它們實際上是用逗號分隔的,而不是整數,然後用逗號分隔並遍歷它並解析出來。) – Corbin

+0

'eval'?哎呀! (我引用了JavaScript社區中廣泛使用的一個表達式:「eval is evil」。) –

+0

您可能想要使用'csv'模塊。 –

回答

0

你所得到的錯誤是:

Traceback (most recent call last): 
    File "stud.py", line 6, in <module> 
    sum = sum + eval(line) 
    File "<string>", line 1 
    tom jones,100, 
      ^
SyntaxError: invalid syntax 

這是因爲你試圖評估「tom jones,100,」作爲Python表達式。這不是一個有效的Python表達式。更不用說在任意字符串上調用eval()是一個非常糟糕的主意。

您需要split該行,使用','作爲分隔符。然後你需要把第二個字段(100),並將其轉換爲int。您可以將此int添加到sum(或total)並繼續。

N.B:sum()是Python中的一個內置函數,您將它隱藏在相同名稱的變量中。我建議使用其他作品,例如total

祝你好運!

+0

我只是不明白沒有看到代碼...對不起,我對此很新 –

+0

我不能爲你做功課。我只能解釋爲什麼你的代碼是以這種方式行事,並且指向正確的方向。如果你按照我的答案中的鏈接,你應該有足夠的信息來完成你的任務。 – Johnsyweb

+0

int(line.split(',',1)[1])是這樣嗎? –

0

首先,您應該嘗試進入Python interactive mode。它使得使用小部分代碼更容易,因爲您可以立即看到會發生什麼。

除了使用eval之外,還可以使用str.split將字符串拆分爲值。爲「12」,是因爲他們仍然字符串

a = '1,2,3' 
b = a.split(',') 
print b 
print b[0] 
print b[0] + b[1] 
print float(b[0]) + float(b[1]) 

原因b[0] + b[1]打印:啓動交互式解釋,並通過線運行下面的代碼行。你需要告訴python把它們作爲數字(使用float()),然後像你期望的那樣工作。


對於額外的信用,你可以嘗試使用Python csv library閱讀和分析文件:

# Tell Python that you are going to use the csv (comma separated value) library 
import csv 

# Open the file 
file = open('marks.csv') 

# Use the csv library to read the file, instead of using "for line in file1" 
markReader = csv.reader(file) 

# Using this for means that each line is read as a list of strings. 
for row in markReader: 

    # Now we get the string we want from the list. 0 would get the name, 1 gets the mark 
    number_as_string = row[1] 

    # We now make the string an actual number, because if we add '10' + '20', we get '1020' instead of 30.   
    number = float(number_as_string) 
+0

修好了,謝謝。我修改了庫參考示例中的代碼。至於作業的問題,教一個人釣魚。 –

+0

我不想讓任何人做我的作業我說我的大部分程序寫得我需要幫助,我不明白這是一個爲期11周的課程,並沒有足夠的時間來學習我需要學習的每一個東西我是一個騙子..感謝 –

+0

我可以發送給你的程序的整個sh * t和cabo​​odle向你展示 –