2016-04-14 66 views
1

我正在爲需要搜索數據庫(csv)的產品的學校做一個項目。它通過將驗證的EAN-8代碼與每行的第0列進行匹配,並在for循環中進行掃描。有一個嘗試,除了試圖匹配代碼,然後顯示產品,除了它是否找不到它,當它打算打印「PRODUCT NOT FOUND,Try again」時。我嘗試了不同的迭代,如果,否則,如果,elif結合嘗試,除了但無濟於事。請幫忙。Python的行爲我不明白

#code is the barcode 
     for row in csv_file: 
      try: 
       if code == row[0]: 
        print("This product is: ", row[1], "\n", "Quantity left in stock: ", row[2], "\n", "Cost: ", row[3], "\n") 
        quant = int(input("How many do you you want?: ")) 
        if quant > int(row[2]): 
         print("We don't have that many, try again") 
         order() 
        else: 
         orderrow = row 
         orderrow[2] = quant 
         orderrow[3] = float(orderrow[3]) * quant 
         totalcost = totalcost + orderrow[3] 
         orderlist.append(orderrow) 


      except: 
       print("ITEM NOT FOUND, TRY AGAIN") 
       order() 
+0

有什麼例外,你期待'除了'要趕上? – user2357112

+0

很明顯,你沒有得到任何異常。我認爲你誤解了「嘗試/除了」實際上做了什麼。 –

回答

0

正確的方法是在找到匹配的行時設置變量。循環完成後,檢查變量以查看是否找到任何內容,如果沒有,則打印該消息。

found = false 
for row in csv_file: 
    if code == row[0]: 
     found = true 
     print("This product is: ", row[1], "\n", "Quantity left in stock: ", row[2], "\n", "Cost: ", row[3], "\n") 
     quant = int(input("How many do you you want?: ")) 
     if quant > int(row[2]): 
      print("We don't have that many, try again") 
      order() 
     else: 
      orderrow = row 
      orderrow[2] = quant 
      orderrow[3] = float(orderrow[3]) * quant 
      totalcost = totalcost + orderrow[3] 
      orderlist.append(orderrow) 
if !found 
    print("ITEM NOT FOUND, TRY AGAIN") 
    order() 
+0

感謝@Barmar這真的幫了大忙! –

5

您需要合適的if-else而不是try-catch。這裏沒有Exception。如何:

for row in csv_file: 
    if code == row[0]: 
     print("This product is: ", row[1], "\n", "Quantity left in stock: ", row[2], "\n", "Cost: ", row[3], "\n") 
     quant = int(input("How many do you you want?: ")) 
     if quant > int(row[2]): 
      print("We don't have that many, try again") 
      order() 
     else: 
      orderrow = row 
      orderrow[2] = quant 
      orderrow[3] = float(orderrow[3]) * quant 
      totalcost = totalcost + orderrow[3] 
      orderlist.append(orderrow) 
    else: 
     print("ITEM NOT FOUND, TRY AGAIN") 
     order() 
+0

這將爲文件中沒有匹配代碼的每一行打印「ITEM NOT FOUND」。 – Barmar

+0

@Barmar我沒有驗證OP的邏輯。只需修復不必要的'try-except'並指向'if-else'。看起來這是所有OP需要在這一點:) – th3an0maly

+0

編輯我的評論。謝謝 – th3an0maly