尝试和除了python代码

时间:2016-02-27 14:38:32

标签: python exception try-catch

我正在尝试在文件中搜索一个数字。如果数字在文件中,它将显示该行。但是,如果不是我想要它未找到产品。我尝试了下面的代码,但没有找到的产品没有显示。

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()

1 个答案:

答案 0 :(得分: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")