Skip to main content
 首页 » 编程设计

我无法理解的 Python 行为

2025年05月04日2598°冷暖

我正在为学校做一个项目,需要在数据库 (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()