2016-02-27 80 views
-1

我正試圖搜索文件中的數字。如果數字在文件中,它將顯示該行。然而,如果它不是我想要它說產品未找到。我嘗試了下面的代碼,但沒有找到產品不顯示。嘗試和除python代碼

def find_item(): 
    product=input("Enter your product number here: ") 
    search=open("products.txt") 

    try: 
     for x in search: 
      if product in x: 
       print(x) 
    except: 
     print("product not found") 


find_item() 
+0

你'產品不found'將僅在嘗試語句產生一些錯誤 – dnit13

+0

感謝dnit13顯示。當我輸入正確的產品編號時,它將顯示列表中的詳細信息。當我在'未找到產品'中輸入錯誤代碼時,不會打印。該程序剛結束 – LTW

+0

是的,因爲該打印語句將永遠不會被執行,除非你在嘗試中出現一些異常 – dnit13

回答

0

如果找不到產品,try下的代碼不會產生任何異常。這個任務就好辦多了一個標誌變量來實現:

found = False 
for x in search: 
    if product in x: 
     print(x) 
     found = True 
     # possibly also break here if the product can only appear once 

if not found: 
    print("product not found") 
+1

這很棒。非常感謝Mureinik – LTW