2015-04-04 44 views
0
def meanRating(afile): 
    rating = 0 
    divider = 0 
    for line in afile: 
     listline = line.split(',') 
     print(listline) 
     rating = rating + int(listline[2]) 
     divider = divider + 1 
    print(rating/divider) 

def main(): 
    file2 = open('blank.txt','w') 
    data = 0 # Just assigning data before the loop 
    while data != '\n': 
     data = input('Enter your data followed by a comma using the Netflix movie rating format. Enter a blank line when you are done.') 
     data = data.split(',') 
     if len(data) != 4: 
      print('That data is incorrect') 
     else: 
      data = ''.join(data) 
      file2.write(data) 
      file2.write('\n') 
    file2.close() 
    file2 = open('blank.txt','r') 
    print('cal') 
    print('This is the average rating of your movie:',meanRating(file2)) 
    file2.close() 
main() 

這裏的問題是,它創建並寫入文件後,它不執行meanRating函數。編輯:只發布當前版本。Python我試圖做一個程序,將數據寫入文件然後讀取該數據

+0

不要'返回數據' – Paul 2015-04-04 18:21:55

+0

刪除。仍然沒有執行meanRating功能 – 2015-04-04 18:24:57

+0

我也刪除了返回'該數據不正確...',這是一個愚蠢的錯誤,它現在打印。 – 2015-04-04 18:27:43

回答

0

的幾個問題與您的代碼:

  • 如果你想允許你的用戶結束時,一個空行插入的支票,任何嘗試之前,否則你就只得到「「這數據是開關輸入不正確'「一遍又一遍例如if data.strip() == "": break

  • data = ''.join(data)應該是data = ','.join(data),因爲後面你會期待它被逗號分隔。

  • 函數meanRating應該return rating/divider而不是隻打印它。
相關問題