I've been trying to search my csv file in python which works so that it outputs the cost of each item etc. But if a wrong GTIN code is input i need it to say it can't find the product. Help is needed. Many Thanks in advance
import csv
with open('PriceList.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
GTINcode = []
Products = []
Quantitys = []
PricePu = []
Totals = []
for row in readCSV:
Product = row[1]
GTIN = row[0]
Quantity = row[2]
Total = row[4]
Price = row[3]
GTINcode.append(GTIN)
Products.append(Product)
Quantitys.append(Quantity)
Totals.append(Total)
PricePu.append(Price)
whatColor = input('Enter the GTIN code of the product you wish:')
coldex = GTINcode.index(whatColor)
theDate = Products[coldex]
info = Quantitys[coldex]
ppi = PricePu[coldex]
tts = Totals[coldex]
print('Your GTIN code of:',whatColor,'is',theDate,"We have",info,"left in stock. The price for each item is",ppi,"and the total cost of this would be",tts)
You need a try and except if the value looked for does not exist. As well as a while loop to keep on trying!
import csv
with open('PriceList.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
GTINcode = []
Products = []
Quantitys = []
PricePu = []
Totals = []
for row in readCSV:
Product = row[1]
GTIN = row[0]
Quantity = row[2]
Total = row[4]
Price = row[3]
GTINcode.append(GTIN)
Products.append(Product)
Quantitys.append(Quantity)
Totals.append(Total)
PricePu.append(Price)
error = True
while error:
whatColor = input('Enter the GTIN code of the product you wish:')
try:
coldex = GTINcode.index(whatColor)
error = False
theDate = Products[coldex]
info = Quantitys[coldex]
ppi = PricePu[coldex]
tts = Totals[coldex]
print('Your GTIN code of:',whatColor,'is',theDate,"We have",info,"left in stock. The price for each item is",ppi,"and the total cost of this would be",tts)
except ValueError:
print('This is not a valid GTIN code')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.