尝试和接受 Python 代码

2024-03-29 10:20:52 发布

您现在位置: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()

Tags: 文件代码ininputsearchyour产品def
1条回答
网友
1楼 · 发布于 2024-03-29 10:20:52

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

相关问题 更多 >