2017-02-08 83 views
0

這是我的數據庫的代碼,我已經使用了一個文本文件,並將其插入到代碼中,但是當它到達第27行時,它出現了錯誤股票文件,接受訂單,併產生一個列表或產品購買

Traceback (most recent call last): 
    File "N:\computing\databse\task 2.py", line 27, in <module> 
    print("you bought", + products[i][1], "at a cost of", +str(products_total)) 
TypeError: bad operand type for unary +: 'str' 

我試着看過很多不同的網站,但我無法弄清楚如何解決這個問題或者代碼有什麼問題,爲什麼它不起作用!其他的一切似乎是工作的罰款,如果有人可以幫助我一點點我將非常感謝:

products = [] 
with open('StockFile.txt','r') as i: 
    for line in i: 
     line = line[:-1] 
     row = line.split(',') 
     products.append(row) 

    print(products) 

total = 0 
items = [] 
answer = "yes" 
while answer == "yes": 
    GTIN = input ("Please input GTIN:") 
    found = False 
    for i in range (0,len(products)): 
     if GTIN == products[i][0]: 
      found = True 
      items.append(GTIN) 
      items.append(products[i][1]) 
      items.append(products[i][2]) 

      quantity = input("How many would you like?") 
      items.append(quantity) 
      product_total = int(quantity) * float (products[i][2]) 
      items.append(product_total) 
      print("you bought", + products[i][1], "at a cost of", +str(products_total)) 

      total = total + products_total 

    if found == False: 
     print("Sorry not a valid number try again") 
    print("DO you want another item?") 
    answer = input() 
for i in range(0,len(items),5): 
    print(items[i], items[i+1], items[i+2], items[i+3], items[i+4]) 
print("total cost of the order is £" +str(total)) 

這裏是我使用的文本文件:

13245627,螺母和螺栓,0.5 34512340,平原括號,1個 56756777,100mm螺栓,2.5 90673412,L形的托架,0.7

回答

0

你必須的代碼行中的錯誤:

print("you bought", + products[i][1], "at a cost of", +str(products_total)) 

嘗試取出+,所以它看起來像:

print("you bought", str(products[i][1]), "at a cost of", str(products_total)) 
0

你似乎是混合印製了一系列的對象有兩種方法:通過用逗號分隔呈現的每個對象作爲單獨的參數,和連接字符串與+運算符。結果,你結束了一個參數+str(products_total)str班不知道該如何處理+之前的標記。

要麼堅持所有ARGS用逗號分隔:

print("you bought", products[i][1], "at a cost of", products_total) 

或連接字符串(在這種情況下,你需要products[i][1]轉換爲str,太):

print("you bought" + str(products[i][1]) + "at a cost of" + str(products_total)) 

更好的是,使用string formatting,您不需要執行以下任一操作:

print("you bought {0} at a cost of {1}".format(products[i][1], products_total))