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?
CodePudding user response:
One solution can be making a custom function that has two parameters: message and type of accepted input:
def enter_data(message, typ):
while True:
try:
v = typ(input(message))
except ValueError:
print(f"That's not an {typ}!")
continue
else:
break
return v
def add_item():
item_num = enter_data("What is the items #?\n", int)
price = enter_data("What is the items price?\n", float)
quant = enter_data("What is the items quantity?\n", int)
while True:
name = enter_data("What is the items name?\n", str)
if name == "":
print("Ha! You have to enter a name!")
continue
break
new_row = [item_num, price, quant, name]
print(new_row)
add_item()
Prints (for example):
What is the items #?
what?
That's not an <class 'int'>!
What is the items #?
3
What is the items price?
what?
That's not an <class 'float'>!
What is the items price?
10
What is the items quantity?
3
What is the items name?
Ha! You have to enter a name!
What is the items name?
Apple
[3, 10.0, 3, 'Apple']