Python 行为我无法理解

Python behaviour I can't understand

我正在为学校做一个项目,需要在数据库 (csv) 中搜索产品。它通过将经过验证的 EAN-8 代码与每行的第 0 列进行匹配来实现这一点,并在 for 循环中进行扫描。有一个尝试,除了尝试匹配代码,然后显示产品,除非找不到它,当它意味着打印"PRODUCT NOT FOUND, TRY AGAIN"。我尝试了 if、else、if、elif 通过 try 组合的不同迭代,除了但无济于事。请帮忙

#code is the barcode
        for row in csv_file:
            try:
                if code == row[0]:
                    print("This product is: ", row[1], "\n", "Quantity left in stock: ", row[2], "\n", "Cost: ", row[3], "\n")
                    quant = int(input("How many do you you want?: "))
                    if quant > int(row[2]):
                        print("We don't have that many, try again")
                        order()
                    else:
                        orderrow = row
                        orderrow[2] = quant
                        orderrow[3] = float(orderrow[3]) * quant
                        totalcost = totalcost + orderrow[3]
                        orderlist.append(orderrow)


            except:
                print("ITEM NOT FOUND, TRY AGAIN")
                order()

你需要一个合适的 if-else,而不是 try-catch。这里没有Exception被抓到。怎么样:

for row in csv_file:
    if code == row[0]:
        print("This product is: ", row[1], "\n", "Quantity left in stock: ", row[2], "\n", "Cost: ", row[3], "\n")
        quant = int(input("How many do you you want?: "))
        if quant > int(row[2]):
            print("We don't have that many, try again")
            order()
        else:
            orderrow = row
            orderrow[2] = quant
            orderrow[3] = float(orderrow[3]) * quant
            totalcost = totalcost + orderrow[3]
            orderlist.append(orderrow)
    else:
        print("ITEM NOT FOUND, TRY AGAIN")
        order()

正确的做法是在找到匹配行时设置一个变量。循环完成后,检查变量以查看是否找到任何内容,如果没有,则打印消息。

found = false
for row in csv_file:
    if code == row[0]:
        found = true
        print("This product is: ", row[1], "\n", "Quantity left in stock: ", row[2], "\n", "Cost: ", row[3], "\n")
        quant = int(input("How many do you you want?: "))
        if quant > int(row[2]):
            print("We don't have that many, try again")
            order()
        else:
            orderrow = row
            orderrow[2] = quant
            orderrow[3] = float(orderrow[3]) * quant
            totalcost = totalcost + orderrow[3]
            orderlist.append(orderrow)
if !found
    print("ITEM NOT FOUND, TRY AGAIN")
    order()