I have the following code which works to input a new item into my dictionary into my list of dictionaries, as well as write it to the csv file.
Here is the following code:
def add_item(self):
while True:
try:
item_num = int(input("What is the items #?\n"))
except ValueError:
print("That's not an int!")
continue
else:
break
while True:
try:
price = float(input("What is the items price?\n"))
except ValueError:
print("Thats not a float!")
continue
else:
break
while True:
try:
quant = int(input("What is the items quantity?\n"))
except ValueError:
print("Thats not an int!")
continue
else:
break
while True:
try:
name = str(input("What is the items name?\n"))
except ValueError:
print("Thats not a string!")
continue
if name == "":
print("Ha! You have to enter a name!")
continue
else:
break
new_row = [item_num, price, quant, name]
with open("Items2.csv", "a+") as fp:
reader = csv.reader(fp)
fp.seek(0)
labels = next(reader, None)
writer = csv.writer(fp)
new_record = dict(zip(labels, new_row))
self.result.append(new_record)
writer.writerow(new_record.values())
print("Item Added! Check Inventory Again to see!")
I was wondering if there was a way to simplify this process and or shorten it? Obviously it is very repetitive, but I would like to keep using loops and exceptions, to make a user enter a correct input, and stay in that loop til they have. Is there any way to simplify this?