2016-02-27 82 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