我正在为学校做一个项目,需要在数据库(csv)中搜索产品。它通过将经过验证的EAN-8代码与每行的第0列匹配,在for循环中扫描来完成此操作。有一个尝试,除了试图匹配代码,然后显示产品,除非它无法找到它,当它意味着打印"产品未找到,再试一次& #34 ;.我尝试了不同的迭代if,else,if,elif结合尝试,除了但无济于事。请帮忙。
#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()
答案 0 :(得分:5)
您需要一个合适的0dp
,而不是if-else
。这里没有try-catch
被抓住。怎么样:
Exception
答案 1 :(得分:0)
执行此操作的正确方法是在找到匹配的行时设置变量。循环完成后,检查变量以查看是否找到了任何内容,如果没有,则打印该消息。
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()