2016-08-15 23 views
-3

「」「」計算在一個文件中輸入查詢值的平均值,代碼產生錯誤的輸出

num = 3 
try:  #set an exception in case of a file Error 

    while num >=0: '''read in values and place them in a file''' 
     value = int(input("Enter values: ")) 
     my_file = open('my_data.txt', 'w+') 
     my_file.write(str(value)) 
     numbers = my_file.readlines() 
     num -=1 
    my_file.close() 

except IOError: 
    print('FILE FAILURE') 

'''iterate to find the sum of the values in a file''' 
total = 0 
    for ln in numbers: 
     total += int(ln) 

'''Calculate the average''' 
avg = total/len(numbers) 
    print("The average is %d"%(avg))#FIXME: does not calculate average 
+1

「代碼產生錯誤的輸出」究竟如何?您應該提供示例輸入和輸出。請注意,您將在每個將其截斷的迭代中打開該文件。你爲什麼寫信給該文件並立即讀取它? – DeepSpace

+0

@DeepSpace,如果我輸入值,例如:2,4,7,5。輸出總是第三個數字。在這個例子中7.謝謝! – Umubale

+0

請參閱我的評論的其餘部分。 – DeepSpace

回答

0

您正在打開的文件寫入「這個簡單的程序將使用文件計算平均」,然後從讀它,並將其分配給一個變量numbers。但是,這個變量不是一個列表,雖然你在做for ln in numbers時將它當作列表對待。

此外,你應該結束寫入基於我如何理解你的代碼\n

到文件中的行,你想:

  • 獲取用戶輸入,並寫入到文件
  • 從文件,讀取數字
  • 從數計算平均

有一個statistics模塊,功能mean,它將爲您執行計算部分。其餘的,你可以(應該)像上面的三個項目符號結構,像這樣:

from statistics import mean 

def inputnumbers(itterations, filename): 
    with open(filename, 'w') as openfile: 
     while itterations > 0: 
      try: 
       value=int(input("value->")) 
      except ValueError: 
       print('Numbers only please') 
       continue 
      openfile.write(str(value) + '\n') 
      itterations -= 1 

def getaveragefromfile(filename): 
    numbers = [] 
    with open(filename, 'r') as openfile: 
     for line in openfile.readlines(): 
      numbers.append(int(line.replace('\n',''))) 
    return mean(numbers) 

def main(): 
    filename = r'c:\testing\my_data.txt' 
    itterations = int(input('how many numbers:')) 
    inputnumbers(itterations, filename) 
    average = getaveragefromfile(filename) 
    print(average) 

if __name__ == '__main__': 
    main() 
相關問題