2016-11-23 32 views
-1

テキストファイルを開き、gtin-8製品コードを入力するかどうかをユーザーに尋ねるコードがあります。しかし、私は製品の総コストを見つけることができません。どんな助けも高く評価されるでしょう!ユーザーリクエストを含むテキストファイルからの読み取りと書き込み

gtin8 name cost 
34512340 plain brackets £0.50 
56756777 100 mm bolts £0.20 
90673412 L-shaped brackets £1.20 
76842309 Screwdriver £3.00 
6 Radiator Key £4.00 
34267891 Panel Saw £12.00 
67532189 Junior Hacksaw £7.00 
98123470 Wrench £8.00 
18653217 Shovel £8.00 
67543891 Hammer £10.00 
23879462 File £7.00 

マイコード:

loop = True 
productsfile = open("Products.txt", "r+") 
recieptfile = open("Receipt.txt", "w") 
search = productsfile.readlines() 
while True: 
     yesno = input("Would you like to type in a gtin-8 product code?(yes/no)") 
     if yesno == "yes": 
      gtin8 = int(input("Please enter your GTIN-8 code: ")) 
      if len(gtin8) == 8: 
        while True: 
          for line in search: 
            if gtin8 in line: 
              productline = line 
              recieptfile = open("Receipt.txt", "w") 
              recieptfile.writelines("\n" + "+") 
              quantity = int(input("What is the quantity of the product you require? ")) 
              itemsplit = productline.split(",") 
              cost = float(itemsplit[3]) 
              totalcost = (cost)*(quantity) 
              recieptfile.writelines("Your total cost is: ", totalcost) 
      else: 
        print("Here is your reciept", "reciept.txt", "r") 
+1

'gten'は整数なので' if len(gtin8)== 8: 'は正しくできません。 –

+0

この問題は修正されていませんが、これを示すエラーが発生しています...トレースバック(最新の最後のコール): ファイル "N:\ Year 10-11 \ Computing \ A453 \ Controlled Assessment Task 2 \ Controlled Assessment Code.py "、行17、 コスト= float(itemsplit.split("、 ")) AttributeError: 'list'オブジェクトには 'split'属性がありません –

答えて

0

が、私はそれがより読みやすく、明確であるように、あなたのスクリプトを固定ここに私のテキストファイルとコード...

テキストファイルです。基本的には、これ以上商品を追加したくないときは、製品を頼むつもりです。また、製品が存在するかどうかをチェックします。製品とその価格を辞書に格納します。

recieptfile = open("Receipt.txt", "w") 
product_lines = open("Products.txt", "r").readlines() 
products = [i.split() for i in product_lines][1:] 
product_costs = dict() 
for i in products: 
    product_costs[i[0]] = float(i[-1][1:]) 

total_cost = 0 
first_item = True 
while True: 
    yesno = input("Would you like to type in a gtin-8 product code?(yes/no)") 
    if yesno == "yes": 
     gtin8 = input("Please enter your GTIN-8 code: ") 
     if gtin8 in product_costs: 
      quantity = int(input("What is the quantity of the product you require? ")) 
      price = product_costs[gtin8] 
      cost = price * quantity 

      if not first_item: 
       recieptfile.write("\t+\n") 
      recieptfile.write("{0}\t{1}".format(gtin8, cost)) 
      total_cost += cost 
      first_item = False 
     else: 
      print("Product not found") 
    else: 
     recieptfile.write("\nYour total cost is: {0}".format(total_cost)) 
     break 
recieptfile.close() 
with open('Receipt.txt', 'r') as recieptfile: 
    print("Here is your reciept:") 
    print(recieptfile.read()) 
+0

コメントありがとうございます!できます! –

+1

あなたの助けを感謝します! –

関連する問題