2016-12-12 9 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

なぜ 'reader'を繰り返しループしていますか? – user2357112

+0

どの配列ですか? 'receipt = []'? 'print()'を使って、コードの異なる場所の変数の値をチェックしてください。たぶんあなたは 'receipt = []'を使ってすべての値を間違った場所で削除するでしょう。 – furas

答えて

0

csvの行をもう一度読み取る前に、stock.seek(0)行26:for row in reader:と呼び出してください。

csv.reader()オブジェクトは、Pythonのfile.read()メソッドのように動作します。ファイルの内容を再度読み取る前に、ファイルリーダーをファイルの先頭にリセットする必要があります。ラインwhile choice=='product':でユーザーの入力をチェックする前に、あなたはすでに一度ライン17csvファイルを読んでいませんでした:

for row in reader: 
    ... 

csv.reader()オブジェクトがまだcsvファイルの内容の末尾に指している、とこれ以上あります読者が読むことができるので、コードは決して次のfor row in reader:ループに入りません。

if barcode in row:で、再びcsv内容を読む前にstock.seek(0)文を挿入し、それを修正するには、ファイルの先頭にcsv.reader()がリセットされますし、アイテムがあなたの配列を埋める表示されるはずです。

+0

それは動作します。ご協力いただきありがとうございます – TheOneWhoLikesToKnow

関連する問題