我正在为学校做一个项目,需要在数据库(csv)中搜索产品.它通过将经过验证的EAN-8代码与每行的第0列匹配,在for循环中扫描来完成此操作.有一个尝试,除了试图匹配代码,然后显示产品,除非它找不到它,当它打算打印"产品未找到,再试".我尝试了不同的迭代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()
Run Code Online (Sandbox Code Playgroud)
你需要一个合适的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()
Run Code Online (Sandbox Code Playgroud)