尝试并排除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()

如果未找到产品,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")

最新更新