2016-12-31 29 views
-2

在我的代碼中,我驗證了用戶輸入的GTIN代碼。如果用戶輸入的數字不是8位數字,並且不在我的文本文件中,則會輸出Product Not Found,但是在測試時當我輸入數字以外的任何東西時,它可以正常工作。然而,當我輸入像0這樣的單個數字時,它完全打破並且說Quantity is not defined,數量是我的一個變量,我不確定爲什麼這麼說。我的驗證有時會中斷

編輯:當我輸入0,其輸出Product Not Found,但仍然給我的錯誤。

file = open("read_it.txt" , "r") 
for line in file: 
      line = line.strip('\n') 
      print(line) 
allprice=[] 
while True: 
    GTIN=(input("please enter GTIN for product or press enter for receipt")) 
    if(GTIN==''): 
     final = sum(allprice) 
     final=str(final) 
     print("total cost {0:33} £{1}".format("is",final)) 
     break 
    else: 
     if GTIN.isnumeric() and len(GTIN)==8 and GTIN in open('read_it.txt').read(): 
      while True: 
       Quantity="" 
       Quantity=(input("Please enter the Quantity")) 
       if Quantity.isdigit(): 
        break 
       else: 
        print("enter a number!") 
     else: 
      print("Product Not Found") 

     with open("read_it.txt", "r") as text_file: 
      for items in text_file: 
       line = items.strip('\r\n').split(",") 
       if GTIN in items: 
        product = line[1] 
        indprice = line[2] 
        finprice = float(indprice)* float(Quantity) 
        finprice=int(finprice) 
        print("{:<10} {:<10} {:<10} £{:<10} £{:<10}".format(GTIN,product,Quantity,indprice,finprice)) 

    allprice.append(finprice) 

回答

0

看來你正在if塊中定義數量。由於「0」不是8位數字,因此數量永遠不會定義,並且由於浮動(數量)而引發錯誤。考慮定義塊之外的數量。

+0

感謝您的回答,但我解決了它。這是因爲代碼的text_file部分沒有用數量部分縮進,所以當我輸入0時,它會跳過詢問數量並直接計算。檢查新代碼。 –

相關問題