2016-12-12 34 views
0

我正在嘗試創建一個像商店一樣工作的程序,但由於某種原因,它不會在需要時將任何內容放入數組中。爲什麼代碼不會將任何東西放入數組中?

CSV文件,我使用看起來像這樣:

24937597 Basic Hatchet 20 
49673494 Hardened Axe 100 
73165248 Steel Axe  500 
26492186 Utility Truck 2000 
54963726 Small Trailer 600 
17667593 Shabby Sawmill 200 
76249648 SawMax 01  5000 
34865729 Basic Hammer 70 
46827616 50mm Nails  0.10 
46827623 20mm Nails  0.05 

我的代碼如下所示:

import csv 
import time 

retry='yes' 
while retry=='yes': 

    receipt=[] 
    total=0 
    numofitems=0 

    with open ('Stock File.csv','r') as stock: 
     reader=csv.reader(stock, delimiter=',') 

     print('Welcome to Wood R Us. Today we are selling:') 
     print(' ') 
     print('GTIN-8 code Product name Price') 
     for row in reader: 
      print(row[0]+' '+row[1]+' '+row[2]) 
     print(' ') 

     choice='product' 
     while choice=='product': 
      inputvalid='yes' 
      barcode=input('Enter the GTIN-8 code of the product you wish to purchase: ') 
      quantity=int(input('Enter the quantity you wish to purchase: ')) 
      for row in reader: 
       if barcode in row: 
        cost=int(row[2]) 
        price=quantity*cost 
        total=total+price 
        receipt.append(barcode+row[1]+str(quantity)+row[2]+str(price)) 
        numofitems=numofitems+1 

      print('Do you want to buy another product or print the receipt?') 
      choice=input('product/receipt ') 

     if choice=='receipt': 
      inputvalid='yes' 
      for i in range(0, numofitems): 
       print(str(receipt[i])) 
       time.wait(0.5) 
      print(' ') 
      print('Total cost of order  '+str(total)) 

     else: 
      inputvalid='no' 

     if inputvalid=='no': 
      print('Invalid input') 

     if inputvalid=='yes': 
      print(' ') 
      print('Do you want to make another purchase?') 
      retry=input('yes/no ') 
     while retry!='yes': 
      while retry!='no': 
       print(' ') 
       print('Invalid input') 
       print('Do you want to make another purchase?') 
       retry=input('yes/no ') 
      retry='yes' 
     retry='no' 
if retry=='no': 
    print('Goodbye! See you again soon!') 

有誰知道如何解決這一問題?

+3

爲什麼在內置布爾值時使用字符串值? –

+0

你爲什麼試圖重複循環閱讀器? – user2357112

+0

是什麼數組? '收據= []'?使用print()來檢查代碼中不同位置的變量值。也許你在錯誤的地方用'receipt = []'刪除了所有的值。 – furas

回答

0

在第26行調用stock.seek(0)for row in reader:再次讀取csv的行。

csv.reader()對象的行爲方式類似於python的file.read()方法,因爲在再次讀取文件內容之前,文件讀取器需要重置爲文件的開頭。之前在行while choice=='product':檢查用戶的輸入,你已經通過csv文件一次在行17閱讀:

for row in reader: 
    ... 

csv.reader()對象在的csv文件的內容到底還是指指點點,沒有更多行讀取器讀取,所以代碼永遠不會進入下一個循環。

要修復它,再次讀取csv內容,在if barcode in row:前插入一個stock.seek(0)聲明,將重置csv.reader()到文件的開頭,你應該看到的物品填寫您的陣列。

+0

它的工作原理。謝謝你的幫助 – TheOneWhoLikesToKnow

相關問題