I have a inventory program that works. I am trying to save out the data (item names and qty) which are held in a list called inventory. So they can be reused for the next time the program is launched and edited at a later date.
My inventory program code:
import os
class Inventory:
def __init__(self):
self.item = []
self.qty = []
def remove(self, name):
ix = self.item.index(name)
self.item.pop(ix)
self.qty.pop(ix)
def add(self, name, qty):
self.item.append(name)
self.qty.append(qty)
def update(self, name, update):
if update >= 0:
self.qty[self.item.index(name)] += update
elif update <= -1:
self.qty[self.item.index(name)] += update
def search(self, name):
pos = self.item.index(name) if name in self.item else -1
if pos >= 0:
return self.item[pos], self.qty[pos]
else:
return None
def __str__(self):
out = ""
zipo = list(zip(self.item, self.qty))
for foobar in zipo:
out += f"Item : {foobar[0]} \nQuantity : {foobar[1]}\n"
out += "----------\n"
return out
def menuDisplay():
"""Display the menu"""
print('=============================')
print('= Inventory Management Menu =')
print('=============================')
print('(1) Add New Item to Inventory')
print('(2) Remove Item from Inventory')
print('(3) Update Inventory')
print('(4) Search Item in Inventory')
print('(5) Print Inventory Report')
print('(99) Quit')
def add_one_item(inventory):
print('Adding Inventory')
print('================')
while True:
try:
new_name = input('Enter the name of the item: ')
assert new_name.isalpha(), "Only letters are allowed!"
new_qty = int(input("Enter the quantity of the item: "))
inventory.add(new_name, new_qty)
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def remove_one_item(inventory):
print('Removing Inventory')
print('==================')
removing = input('Enter the item name to remove from inventory: ')
inventory.remove(removing)
def ask_exit_or_continue():
return int(input('Enter 98 to continue or 99 to exit: '))
def update_inventory(inventory):
print('Updating Inventory')
print('==================')
item = input('Enter the item to update: ')
update = int(input(
"Enter the updated quantity. Enter 5 for additional or -5 for less: "))
inventory.update(item, update)
def search_inventory(inventory):
print('Searching Inventory')
print('===================')
search = input('Enter the name of the item: ')
result = inventory.search(search)
if result is None:
print("Item not in inventory")
else:
name, qty = result
print('Item: ', name)
print('Quantity: ', qty)
print('----------')
def print_inventory(inventory):
print('Current Inventory')
print('=================')
print(inventory)
def main():
inventory = Inventory()
while True:
try:
menuDisplay()
CHOICE = int(input("Enter choice: "))
if CHOICE in [1, 2, 3, 4, 5]:
if CHOICE == 1:
add_one_item(inventory)
elif CHOICE == 2:
remove_one_item(inventory)
elif CHOICE == 3:
update_inventory(inventory)
elif CHOICE == 4:
search_inventory(inventory)
elif CHOICE == 5:
print_inventory(inventory)
exit_choice = ask_exit_or_continue()
if exit_choice == 99:
exit()
elif CHOICE == 99:
exit()
except Exception as e:
print("Invalid choice! try again!"+str(e))
print()
# If the user pick an invalid choice,
# the program will come to here and
# then loop back.
main()
The program is called Cleancopy.py and I am trying to save the data to a TextEdit file or excel document called Inventory.
The code that is suppose to export the name and qty in the list called inventory.
How do I fix this? This is my first time trying to save this data. Thank you for your time.
The quickest way to save and retrieve lists is to save them to a text file, then use eval to read the lists. For the inventory, update the data file each time an item is added or removed. Load the data when the inventory object if first instantiated.
Try this update:
class Inventory:
def __init__(self):
.....
self.load()
def remove(self, name):
....
self.save()
def add(self, name, qty):
.....
self.save()
def update(self, name, update):
.....
self.save()
.....
def save(self):
with open('inventory.dat','w') as f:
f.write(str(self.item) + '\n' + str(self.qty))
def load(self):
from os import path
if path.exists('inventory.dat'):
with open('inventory.dat','r') as f:
lns = f.readlines()
self.item = eval(lns[0])
self.qty = eval(lns[1])
For more data, you should use a csv file.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have an inventory program that works but has one problem.
Search(option 4) needs to be able to search an inventory item by characters in its name. For example, if Oranges are in inventory, I should be able to type or and it can pull it up and display all the information about it including name, qty, and ID number.
The problem: Currently search only works if you type in the ID number.
Question: how do I change over this search function without causing issues for my other program options. I will attach the full program, but the problem is in def search.
Reason for providing full code: Every time I try to make an edit to the def search, add (Option 1)either does not work or overwrites inventory items that share the same ID number (it shouldn't accept duplications). Same with update (Option 3).
Code:
import os
import json
class Inventory:
def __init__(self):
#AT LAUNCH GROUPS AND LOADING FUNCTION
self.items = {}
self.load()
def remove(self, ID):
#REMOVING ITEMS FOR LISTS AND OUTPUT DOCUMENT
del self.items[str(ID)]
self.save()
def add(self, ID, name, qty):
#ADDING ITEMS FOR LISTS AND OUTPUT DOCUMENT
self.items[str(ID)] = {"name": name, "qty": qty}
self.save()
def update(self, ID, update):
#UPDATING ITEMS FOR LISTS AND OUTPUT DOCUMENT
self.items[str(ID)]["qty"] += update
self.save()
def search(self, query):
for id in self.items:
if str(query) == id:
return id, self.items[id]['name'], self.items[id]['qty']
return None
def __str__(self):
#FORMATTING
out = ""
for id, d in self.items.items():
out += f"ID Number : {id} \nItem Name : {d['name']}\nQuantity : {d['qty']}\n"
out += "----------\n"
return out
def save(self):
#WHERE TO SAVE TO
with open('data.txt','w') as outfile:
json.dump(self.items, outfile)
def load(self):
#WHERE TO PUT DATA FROM WHEN RELAUNCHING PROGRAM
try:
with open('data.txt','r') as json_file:
self.items = json.load(json_file)
except:
print("Can't load old inventory, starting fresh")
self.items = {}
def menuDisplay():
#MENU FOR PROGRAM
"""Display the menu"""
print('=============================')
print('= Inventory Management Menu =')
print('=============================')
print('(1) Add New Item to Inventory')
print('(2) Remove Item from Inventory')
print('(3) Update Inventory')
print('(4) Search Item in Inventory')
print('(5) Print Inventory Report')
print('(99) Quit')
def add_one_item(inventory):
#ADDING PROMPT AND ERROR CHECKING
print('Adding Inventory')
print('================')
while True:
try:
new_ID = int(input("Enter an ID number for the item: "))
if inventory.search(new_ID):
print("ID number is taken, please enter a different ID number")
continue
new_name = input('Enter the name of the item: ')
new_qty = int(input("Enter the quantity of the item: "))
inventory.add(new_ID, new_name, new_qty)
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def remove_one_item(inventory):
#REMOVING PROMPT AND ERROR CHECKING
print('Removing Inventory')
print('==================')
removing = int(input("Enter the item's ID number to remove from inventory: "))
inventory.remove(removing)
def ask_exit_or_continue():
#OPTION TO CONTINUE OR QUITE PROGRAM
return int(input('Enter 98 to continue or 99 to exit: '))
def update_inventory(inventory):
#UPDATING PROMPT AND ERROR CHECKING
print('Updating Inventory')
print('==================')
while True:
try:
ID = int(input("Enter the item's ID number to update: "))
if inventory.search(ID):
update = int(input("Enter the updated quantity. Enter 5 for additional or -5 for less: "))
inventory.update(ID, update)
else:
print("ID number is not in the system, please enter a different ID number")
continue
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def search_inventory(inventory):
#SEARCHING PROMPT AND ERROR CHECKING
print('Searching Inventory')
print('===================')
search = input("Enter the name of the item: ")
result = inventory.search(search)
if result is None:
print("Item not in inventory")
else:
ID, name, qty = result
print('ID Number: ', ID)
print('Item: ', name)
print('Quantity: ', qty)
print('----------')
def print_inventory(inventory):
#PRINT CURRENT LIST OF ITEMS IN INVENTORY
print('Current Inventory')
print('=================')
print(inventory)
def main():
#PROGRAM RUNNING COMMAND AND ERROR CHECKING
inventory = Inventory()
while True:
try:
menuDisplay()
CHOICE = int(input("Enter choice: "))
if CHOICE in [1, 2, 3, 4, 5]:
if CHOICE == 1:
add_one_item(inventory)
elif CHOICE == 2:
remove_one_item(inventory)
elif CHOICE == 3:
update_inventory(inventory)
elif CHOICE == 4:
search_inventory(inventory)
elif CHOICE == 5:
print_inventory(inventory)
exit_choice = ask_exit_or_continue()
if exit_choice == 99:
exit()
elif CHOICE == 99:
exit()
except Exception as e:
print("Invalid choice! try again!"+str(e))
print()
# If the user pick an invalid choice,
# the program will come to here and
# then loop back.
main()
Does this solve your problem?
def search(self, query):
for id in self.items:
if str(query) == id or self.items[id]['name'].startswith(str(query)):
return id, self.items[id]['name'], self.items[id]['qty']
return None
Not case sensitive by converting name and query to lowercase first:
def search(self, query):
for id in self.items:
if str(query) == id or self.items[id]['name'].lower().startswith(str(query).lower()):
return id, self.items[id]['name'], self.items[id]['qty']
return None
I have a program that has a search option that if chicken or Chicken is in inventory it will pull up the item by just typing chi (not case-sensitive). The issue is how do I make the function return all items that contain chi?
For example if I have Chickens, chicken, chickens, and Chicken in inventory I should be able to type in chi and it should print out all the information about each item.
Affected Code (not full program):
def search(self, query):
#SEARCHING DATA BASED ON CLOSEST CHARACTER MATCH - NOT CASE SENSITIVE
for id in self.items:
if str(query) == id or self.items[id]['name'].lower().startswith(str(query).lower()):
return id, self.items[id]['name'], self.items[id]['qty']
return None
Full Code for testing purposes:
import os
import json
class Inventory:
def __init__(self):
#AT LAUNCH GROUPS AND LOADING FUNCTION
self.items = {}
self.load()
def remove(self, ID):
#REMOVING ITEMS FOR LISTS AND OUTPUT DOCUMENT
del self.items[str(ID)]
self.save()
def add(self, ID, name, qty):
#ADDING ITEMS FOR LISTS AND OUTPUT DOCUMENT
self.items[str(ID)] = {"name": name, "qty": qty}
self.save()
def update(self, ID, update):
#UPDATING ITEMS FOR LISTS AND OUTPUT DOCUMENT
self.items[str(ID)]["qty"] += update
self.save()
def search(self, query):
#SEARCHING DATA BASED ON CLOSEST CHARACTER MATCH - NOT CASE SENSITIVE
found = []
for id in self.items:
if str(query) == id or self.items[id]['name'].lower().startswith(str(query).lower()):
found.append(
(id, self.items[id]['name'], self.items[id]['qty'])
)
return found
def __str__(self):
#FORMATTING
out = ""
for id, d in self.items.items():
out += f"ID Number : {id} \nItem Name : {d['name']}\nQuantity : {d['qty']}\n"
out += "----------\n"
return out
def save(self):
#WHERE TO SAVE TO
with open('data.txt','w') as outfile:
json.dump(self.items, outfile)
def load(self):
#WHERE TO PUT DATA FROM WHEN RELAUNCHING PROGRAM
try:
with open('data.txt','r') as json_file:
self.items = json.load(json_file)
except:
print("Can't load old inventory, starting fresh")
self.items = {}
def menuDisplay():
#MENU FOR PROGRAM
"""Display the menu"""
print('=============================')
print('= Inventory Management Menu =')
print('=============================')
print('(1) Add New Item to Inventory')
print('(2) Remove Item from Inventory')
print('(3) Update Inventory')
print('(4) Search Item in Inventory')
print('(5) Print Inventory Report')
print('(99) Quit')
def add_one_item(inventory):
#ADDING PROMPT AND ERROR CHECKING
print('Adding Inventory')
print('================')
while True:
try:
new_ID = int(input("Enter an ID number for the item: "))
if inventory.search(new_ID):
print("ID number is taken, please enter a different ID number")
continue
new_name = input('Enter the name of the item: ')
new_qty = int(input("Enter the quantity of the item: "))
inventory.add(new_ID, new_name, new_qty)
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def remove_one_item(inventory):
#REMOVING PROMPT AND ERROR CHECKING
print('Removing Inventory')
print('==================')
while True:
try:
removing = int(input("Enter the item's ID number to remove from inventory: "))
if inventory.search(removing):
inventory.remove(removing)
else:
print("Item not in inventory")
continue
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def ask_exit_or_continue():
#OPTION TO CONTINUE OR QUITE PROGRAM
return int(input('Enter 98 to continue or 99 to exit: '))
def update_inventory(inventory):
#UPDATING PROMPT AND ERROR CHECKING
print('Updating Inventory')
print('==================')
while True:
try:
ID = int(input("Enter the item's ID number to update: "))
if inventory.search(ID):
update = int(input("Enter the updated quantity. Enter 5 for additional or -5 for less: "))
inventory.update(ID, update)
else:
print("ID number is not in the system, please enter a different ID number")
continue
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def search_inventory(inventory):
#SEARCHING PROMPT AND ERROR CHECKING
print('Searching Inventory')
print('===================')
while True:
try:
search = input("Enter the name of the item: ")
result = inventory.search(search)
if result is None:
print("Item not in inventory")
continue
else:
ID, name, qty = result
print('ID Number: ', ID)
print('Item: ', name)
print('Quantity: ', qty)
print('----------')
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def print_inventory(inventory):
#PRINT CURRENT LIST OF ITEMS IN INVENTORY
print('Current Inventory')
print('=================')
print(inventory)
def main():
#PROGRAM RUNNING COMMAND AND ERROR CHECKING
inventory = Inventory()
while True:
try:
menuDisplay()
CHOICE = int(input("Enter choice: "))
if CHOICE in [1, 2, 3, 4, 5]:
if CHOICE == 1:
add_one_item(inventory)
elif CHOICE == 2:
remove_one_item(inventory)
elif CHOICE == 3:
update_inventory(inventory)
elif CHOICE == 4:
search_inventory(inventory)
elif CHOICE == 5:
print_inventory(inventory)
exit_choice = ask_exit_or_continue()
if exit_choice == 99:
exit()
elif CHOICE == 99:
exit()
except Exception as e:
print("Invalid choice! try again!"+str(e))
print()
# If the user pick an invalid choice,
# the program will come to here and
# then loop back.
main()
For a more general answer, if you just want to find the subset of items that contain a substring, this is a good solution:
def subset_contains(input_word, valid_words):
match_list = [word for word in valid_words if input_word in word]
return match_list
running this code:
valid_words = ['chicken', 'cheese', 'chess', 'dog', 'coach']
print(subset_contains('ch', valid_words))
results in this output:
['chicken', 'cheese', 'chess', 'coach']
Here's some more in depth code that might be more like what you're looking for
#defining object, which has a name and description
class object:
def __init__(self, name, info):
self.name = name
self.info = info
#returns a subset of a list where the name contains a string
def return_contains(match_name, objects):
match_list = [obj for obj in objects if match_name in obj.name]
return match_list
#defining objects
objects = [object('chicken', 'chicken 1'),
object('chicken', 'chicken 2'),
object('chicken', 'chicken 3'),
object('coach', 'teaches chickens'),
object('boat', 'im boat')]
#doing the filtering
result = return_contains('ch', objects)
#printing out the results
for r in result:
print('name: {}, description: {}'.format(r.name, r.info))
output:
name: chicken, description: chicken 1
name: chicken, description: chicken 2
name: chicken, description: chicken 3
name: coach, description: teaches chickens
Right now you're just returning the first one you find. Instead, you need to make a list of all the ones you find, and return that:
def search(self, query):
#SEARCHING DATA BASED ON CLOSEST CHARACTER MATCH - NOT CASE SENSITIVE
found = []
for id in self.items:
if str(query) == id or self.items[id]['name'].lower().startswith(str(query).lower()):
found.append(
(id, self.items[id]['name'], self.items[id]['qty'])
)
return found
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have an inventory program that works but has one problem. My program lets you add, remove, update, search, and print inventory items, qty, and ID number. Search(option 4) needs to be able to search an inventory item by characters in its name. For example, if Oranges are in inventory, I should be able to type or and it can pull it up and display all the information about it including name, qty, and ID number.
The problem: Currently search only works if you type in the ID number.
Question: how do I change over this search function without causing issues for my other program options. I will attach the full program, but the problem is in def search.
Code:
import os
import json
class Inventory:
def __init__(self):
#AT LAUNCH GROUPS AND LOADING FUNCTION
self.items = {}
self.load()
def remove(self, ID):
#REMOVING ITEMS FOR LISTS AND OUTPUT DOCUMENT
del self.items[str(ID)]
self.save()
def add(self, ID, name, qty):
#ADDING ITEMS FOR LISTS AND OUTPUT DOCUMENT
self.items[str(ID)] = {"name": name, "qty": qty}
self.save()
def update(self, ID, update):
#UPDATING ITEMS FOR LISTS AND OUTPUT DOCUMENT
self.items[str(ID)]["qty"] += update
self.save()
def search(self, query):
for id in self.items:
if str(query) == id:
return id, self.items[id]['name'], self.items[id]['qty']
return None
def __str__(self):
#FORMATTING
out = ""
for id, d in self.items.items():
out += f"ID Number : {id} \nItem Name : {d['name']}\nQuantity : {d['qty']}\n"
out += "----------\n"
return out
def save(self):
#WHERE TO SAVE TO
with open('data.txt','w') as outfile:
json.dump(self.items, outfile)
def load(self):
#WHERE TO PUT DATA FROM WHEN RELAUNCHING PROGRAM
try:
with open('data.txt','r') as json_file:
self.items = json.load(json_file)
except:
print("Can't load old inventory, starting fresh")
self.items = {}
def menuDisplay():
#MENU FOR PROGRAM
"""Display the menu"""
print('=============================')
print('= Inventory Management Menu =')
print('=============================')
print('(1) Add New Item to Inventory')
print('(2) Remove Item from Inventory')
print('(3) Update Inventory')
print('(4) Search Item in Inventory')
print('(5) Print Inventory Report')
print('(99) Quit')
def add_one_item(inventory):
#ADDING PROMPT AND ERROR CHECKING
print('Adding Inventory')
print('================')
while True:
try:
new_ID = int(input("Enter an ID number for the item: "))
if inventory.search(new_ID):
print("ID number is taken, please enter a different ID number")
continue
new_name = input('Enter the name of the item: ')
new_qty = int(input("Enter the quantity of the item: "))
inventory.add(new_ID, new_name, new_qty)
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def remove_one_item(inventory):
#REMOVING PROMPT AND ERROR CHECKING
print('Removing Inventory')
print('==================')
removing = int(input("Enter the item's ID number to remove from inventory: "))
inventory.remove(removing)
def ask_exit_or_continue():
#OPTION TO CONTINUE OR QUITE PROGRAM
return int(input('Enter 98 to continue or 99 to exit: '))
def update_inventory(inventory):
#UPDATING PROMPT AND ERROR CHECKING
print('Updating Inventory')
print('==================')
while True:
try:
ID = int(input("Enter the item's ID number to update: "))
if inventory.search(ID):
update = int(input("Enter the updated quantity. Enter 5 for additional or -5 for less: "))
inventory.update(ID, update)
else:
print("ID number is not in the system, please enter a different ID number")
continue
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def search_inventory(inventory):
#SEARCHING PROMPT AND ERROR CHECKING
print('Searching Inventory')
print('===================')
search = input("Enter the name of the item: ")
result = inventory.search(search)
if result is None:
print("Item not in inventory")
else:
ID, name, qty = result
print('ID Number: ', ID)
print('Item: ', name)
print('Quantity: ', qty)
print('----------')
def print_inventory(inventory):
#PRINT CURRENT LIST OF ITEMS IN INVENTORY
print('Current Inventory')
print('=================')
print(inventory)
def main():
#PROGRAM RUNNING COMMAND AND ERROR CHECKING
inventory = Inventory()
while True:
try:
menuDisplay()
CHOICE = int(input("Enter choice: "))
if CHOICE in [1, 2, 3, 4, 5]:
if CHOICE == 1:
add_one_item(inventory)
elif CHOICE == 2:
remove_one_item(inventory)
elif CHOICE == 3:
update_inventory(inventory)
elif CHOICE == 4:
search_inventory(inventory)
elif CHOICE == 5:
print_inventory(inventory)
exit_choice = ask_exit_or_continue()
if exit_choice == 99:
exit()
elif CHOICE == 99:
exit()
except Exception as e:
print("Invalid choice! try again!"+str(e))
print()
# If the user pick an invalid choice,
# the program will come to here and
# then loop back.
main()
Add by parameter and send that along with your query.
def search(self, query, by):
if by == "id":
for id in self.items:
if str(query) == id:
return id, self.items[id]['name'], self.items[id]['qty']
elif by == "name":
for id in self.items:
if str(query) == self.items[id]['name']:
return id, self.items[id]['name'], self.items[id]['qty']
elif by == "qty":
for id in self.items:
if str(query) == self.items[id]['qty']:
return id, self.items[id]['name'], self.items[id]['qty']
return None
How do I convert my search function from find data based on ID number to finding the item based on item name entitled 'name'?
Meaning if I have ID: 1 , name: apple , qty: 100 currently if I type in 1 it finds the data for all three fields. But how do I change it so it accepts app (short for apple) and pulls up all three fields? I attached the full code as I believe that to resolve this issue you need the whole program.
But the heart of the issue is located in def search.
Full program code:
import os
import json
class Inventory:
def __init__(self):
#AT LAUNCH GROUPS AND LOADING FUNCTION
self.items = {}
self.load()
def remove(self, ID):
#REMOVING ITEMS FOR LISTS AND OUTPUT DOCUMENT
del self.items[str(ID)]
self.save()
def add(self, ID, name, qty):
#ADDING ITEMS FOR LISTS AND OUTPUT DOCUMENT
self.items[str(ID)] = {"name": name, "qty": qty}
self.save()
def update(self, ID, update):
#UPDATING ITEMS FOR LISTS AND OUTPUT DOCUMENT
self.items[str(ID)]["qty"] += update
self.save()
def search(self, ID):
#SEARCHING ITEMS FOR LISTS
item = self.items.get(str(ID), None)
if item:
return ID, item['name'], item['qty']
else:
return None
def __str__(self):
#FORMATTING
out = ""
for id, d in self.items.items():
out += f"ID Number : {id} \nItem Name : {d['name']}\nQuantity : {d['qty']}\n"
out += "----------\n"
return out
def save(self):
#WHERE TO SAVE TO
with open('data.txt','w') as outfile:
json.dump(self.items, outfile)
def load(self):
#WHERE TO PUT DATA FROM WHEN RELAUNCHING PROGRAM
try:
with open('data.txt','r') as json_file:
self.items = json.load(json_file)
except:
print("Can't load old inventory, starting fresh")
self.items = {}
def menuDisplay():
#MENU FOR PROGRAM
"""Display the menu"""
print('=============================')
print('= Inventory Management Menu =')
print('=============================')
print('(1) Add New Item to Inventory')
print('(2) Remove Item from Inventory')
print('(3) Update Inventory')
print('(4) Search Item in Inventory')
print('(5) Print Inventory Report')
print('(99) Quit')
def add_one_item(inventory):
#ADDING PROMPT AND ERROR CHECKING
print('Adding Inventory')
print('================')
while True:
try:
new_ID = int(input("Enter an ID number for the item: "))
if inventory.search(new_ID):
print("ID number is taken, please enter a different ID number")
continue
new_name = input('Enter the name of the item: ')
new_qty = int(input("Enter the quantity of the item: "))
inventory.add(new_ID, new_name, new_qty)
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def remove_one_item(inventory):
#REMOVING PROMPT AND ERROR CHECKING
print('Removing Inventory')
print('==================')
removing = int(input("Enter the item's ID number to remove from inventory: "))
inventory.remove(removing)
def ask_exit_or_continue():
#OPTION TO CONTINUE OR QUITE PROGRAM
return int(input('Enter 98 to continue or 99 to exit: '))
def update_inventory(inventory):
#UPDATING PROMPT AND ERROR CHECKING
print('Updating Inventory')
print('==================')
while True:
try:
ID = int(input("Enter the item's ID number to update: "))
if inventory.search(ID):
update = int(input("Enter the updated quantity. Enter 5 for additional or -5 for less: "))
inventory.update(ID, update)
else:
print("ID number is not in the system, please enter a different ID number")
continue
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
def search_inventory(inventory):
#SEARCHING PROMPT AND ERROR CHECKING
print('Searching Inventory')
print('===================')
search = input("Enter the name of the item: ")
result = inventory.search(search)
if result is None:
print("Item not in inventory")
else:
ID, name, qty = result
print('ID Number: ', ID)
print('Item: ', name)
print('Quantity: ', qty)
print('----------')
def print_inventory(inventory):
#PRINT CURRENT LIST OF ITEMS IN INVENTORY
print('Current Inventory')
print('=================')
print(inventory)
def main():
#PROGRAM RUNNING COMMAND AND ERROR CHECKING
inventory = Inventory()
while True:
try:
menuDisplay()
CHOICE = int(input("Enter choice: "))
if CHOICE in [1, 2, 3, 4, 5]:
if CHOICE == 1:
add_one_item(inventory)
elif CHOICE == 2:
remove_one_item(inventory)
elif CHOICE == 3:
update_inventory(inventory)
elif CHOICE == 4:
search_inventory(inventory)
elif CHOICE == 5:
print_inventory(inventory)
exit_choice = ask_exit_or_continue()
if exit_choice == 99:
exit()
elif CHOICE == 99:
exit()
except Exception as e:
print("Invalid choice! try again!"+str(e))
print()
# If the user pick an invalid choice,
# the program will come to here and
# then loop back.
main()
Add the function below or replace the existing search function:
def search_name(self, name):
#SEARCHING ITEMS FOR name
for id, item in self.items.items():
if item['name'].startswith(name):
return id, item['name'], item['qty']
return None
I have taken what was once a class project and turned it into something more usable for work. My program is designed as an inventory system. I have currently ensured that my program can export data to a text file, and import that data at request if the program is ever closed. I cannot edit the data after import unless I add new data to the list first, or add new data to the list then import.
I think the reason why it isn't working is because the data imported from the list doesn't have a logical position yet until new data is added.
class Inventory:
def __init__(self):
self.item = ""
self.amount = 0
self.asset_tag = 0
self.notes = ""
def add_inventory(self):
self.item = input("Enter item: ")
self.amount = int(input("How many? "))
self.asset_tag = int(input("Enter Asset Tag if available. Enter 0 if not tagged. "))
self.notes = input("Please add any additional information: ")
def __str__(self):
return('Item: %s Amount: %d Asset Tag: %d Notes: %s' %
(self.item, self.amount, self.asset_tag, self.notes))
inventory_list = []
def edit(inventory_list):
pos = int(input('Enter the position of the item you would like to edit: '))
new_inventory = item.add_inventory()
new_inventory = item.__str__()
inventory_list[pos-1] = new_inventory
print('Inventory has been updated. If the amount is now 0 please notify.')
while True:
print("""
1. Add new inventory.
2. Remove item from inventory.
3. View inventory.
4. Update current inventory.
5. Export inventory to file.
6. Import Inventory file
7. Quit
""")
ans = input('What would you like to do? ')
if ans == "1":
item = Inventory()
item.add_inventory()
inventory_list.append(item.__str__())
elif ans == "2":
for i in inventory_list:
inventory_list.pop(int(input('Enter position of item to remove: ')))
print('Inventory item removed successfully!')
elif ans == "3":
print('\n'.join(map(str, inventory_list)))
elif ans == "4":
edit(inventory_list)
elif ans == "5":
f = open('Inventory_List.txt', 'w')
for ele in inventory_list:
f.write(ele+'\n')
f.close()
elif ans == "6":
with open('Inventory_List.txt') as f:
data = f.read().splitlines()
print(data)
inventory_list.extend(data)
elif ans == "7":
break
else:
print('Invalid entry, try again.')```
item is not defined in the function edit before it gets utilized.