Here is the pseudo-code for an Over Produced Management System:
Add memory library module
Prompt; 1)search for item, 2)add over produced item
If search for item
Prompt input item number
If item number in database print available quantity
Else print “None available”
Else if add over produced item
Prompt input item number
If item number in database
Prompt “how many”
Add quantity to inventory
Else if item number not in inventory
Add item to inventory with quantity
db = {}
while True:
if raw_input("Prompt; 1)search for item, 2)add over produced item > ") == "1":
item = raw_input("Item number? > ")
if item in db:
print("Available: " + str(db[item]))
else:
print("None available")
else:
item = raw_input("Item number? > ")
qty = int(raw_input("Quantity? > "))
if item in db:
db[item] += qty
else:
db[item] = qty
Related
I am trying to append items to a list, and when I type the word "quit" the loop should stop, and then print the items I have on my list, but the loop continues and still asks me the second question on the loop, which I think should not be happening.
itemName = ''
itemPrice = '0.0'
while itemName != 'quit'.lower().strip():
itemName = input('What item would you like to add?')
items.append(itemName + ' $' + itemPrice)
itemPrice = input(f'What is the price of {itemName}?')
for item in items[:-1]:
print(item)
I see one problem, you have your .lower().strip on the wrong side.
Also, I would suggest using break so that your code won't ask for a price if quit is inputted.
items=[]
itemName = ''
itemPrice = '0.0'
while True:
itemName = input('What item would you like to add?')
if itemName.lower().strip() == 'quit':
break
items.append(itemName + ' $' + itemPrice)
itemPrice = input(f'What is the price of {itemName}?')
for item in items[:-1]:
print(item)
The code only checks if you wrote quit after it asks both questions. Also, you should put your .lower().strip() after the input() function. Your code always lowercases and strips the string 'quit'. You can put an if statement after the first question with a break to prevent your code from asking you the second question after you typed 'quit' for the first question.
Try to study this.
items = [] # storage
totalPrice = 0.0
while True:
itemName = input('What item would you like to add? ')
if itemName.lower() == 'quit':
break
itemPrice = input(f'What is the price of {itemName}? ') # ask the price before saving the item
if itemPrice.lower() == 'quit':
break
totalPrice += float(itemPrice) # convert str to float
items.append(f'{itemName} $ {itemPrice}') # Save to storage
print('items:')
for item in items:
print(item)
print()
print(f'total price: $ {totalPrice}')
Output
What item would you like to add? shoes
What is the price of shoes? 600.75
What item would you like to add? bag
What is the price of bag? 120.99
What item would you like to add? quit
items:
shoes $ 600.75
bag $ 120.99
total price: $ 721.74
I have an inventory program that stores the ID number, item name, and the quantity in three different lists. These three lists are combined in an inventory list but, when the data is saves to a TextEdit document it stores the data in three different lists. How do I save this data in one dictionary. First ID number, item name, then qty.
Here is the full program code:
import os
class Inventory:
def __init__(self):
#AT LAUNCH GROUPS AND LOADING FUNCTION
self.ID = []
self.item = []
self.qty = []
self.load()
def remove(self, ID):
#REMOVING ITEMS FOR LISTS AND OUTPUT DOCUMENT
ix = self.ID.index(ID)
self.ID.pop(ix)
self.item.pop(ix)
self.qty.pop(ix)
self.save()
def add(self, ID, name, qty):
#ADDING ITEMS FOR LISTS AND OUTPUT DOCUMENT
self.ID.append(ID)
self.item.append(name)
self.qty.append(qty)
self.save()
def update(self, ID, update):
#UPDATING ITEMS FOR LISTS AND OUTPUT DOCUMENT
if update >= 0:
self.qty[self.ID.index(ID)] += update
elif update <= -1:
self.qty[self.ID.index(ID)] += update
self.save()
def search(self, ID):
#SEARCHING ITEMS FOR LISTS
pos = self.ID.index(ID) if ID in self.ID else -1
if pos >= 0:
return self.ID[pos], self.item[pos], self.qty[pos]
else:
return None
def __str__(self):
#FORMATTING
out = ""
zipo = list(zip(self.ID, self.item, self.qty))
for foobar in zipo:
out += f"ID Number : {foobar[0]} \nItem Name : {foobar[1]}\nQuantity : {foobar[2]}\n"
out += "----------\n"
return out
def save(self):
#WHERE TO SAVE TO
with open('inventory.dat','w') as f:
f.write(str(self.ID) + '\n' + str(self.item) + '\n' + str(self.qty))
def load(self):
#WHERE TO PUT DATA FROM WHEN RELAUNCHING PROGRAM
from os import path
if path.exists('inventory.dat'):
with open('inventory.dat','r') as f:
lns = f.readlines()
self.ID = eval(lns[0])
self.item = eval(lns[1])
self.qty = eval(lns[2])
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 new_ID in inventory.ID:
print("ID number is taken, please enter a different ID number")
continue
new_name = input('Enter the name of the item: ').lower()
assert new_name.isalpha(), "Only letters are allowed!"
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('==================')
ID = int(input("Enter the item's ID number to update: "))
update = int(input("Enter the updated quantity. Enter 5 for additional or -5 for less: "))
inventory.update(ID, update)
def search_inventory(inventory):
#SEARCHING PROMPT AND ERROR CHECKING
print('Searching Inventory')
print('===================')
search = int(input("Enter the ID number 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()
Thank you in advance.
Don't use 3 lists, use a dictionary containing dictionaries. The keys of the main dictionary will be the IDs, and the values will be dictionaries containing the name and quantity.
You can use JSON or pickle to save and load the data.
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[ID]
self.save()
def add(self, ID, name, qty):
#ADDING ITEMS FOR LISTS AND OUTPUT DOCUMENT
self.items[ID] = {"name": name, "qty": qty}
self.save()
def update(self, ID, update):
#UPDATING ITEMS FOR LISTS AND OUTPUT DOCUMENT
self.items[ID]["qty"] += update
self.save()
def search(self, ID):
#SEARCHING ITEMS FOR LISTS
item = self.items.get(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('inventory.dat','w') as f:
json.dump(self.items, f)
def load(self):
#WHERE TO PUT DATA FROM WHEN RELAUNCHING PROGRAM
try:
with open('inventory.dat','r') as f:
self.items = json.load(f)
except:
print("Can't load old inventory, starting fresh")
self.items = {}
You should avoid accessing attributes directly outside the class, as it makes it difficult to reimplement the class so
if new_ID in inventory.ID:
should be
if inventory.search(new_ID):
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
How do I fix this?
Full program code for testing:
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
output = []
for id in self.items:
if str(query) == id or self.items[id]['name'].lower().startswith(str(query).lower()):
output.append((id, self.items[id]['name'], self.items[id]['qty']))
if output: return output
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('==================')
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:
for found in result:
ID, name, qty = found
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()
def search(self, query):
#SEARCHING DATA BASED ON CLOSEST CHARACTER MATCH - NOT CASE SENSITIVE
output = []
for id in self.items:
if str(query) == id or self.items[id]['name'].lower().startswith(str(query).lower()):
output.append((id, self.items[id]['name'], self.items[id]['qty']))
if output:
return output
else:
return None
If you find this unexplainable, maybe I got the question wrong. You should try and explain better more.
The code returns the first match. This search returns all matches.
def search(self, query):
""" Search items for all matching id's in query.
"""
output = [id for id in self.items if str(query).upper() in id.upper()]
return output if output != [] else None
As a stand-alone demo I constructed a Class having a database of 3 items and a search method.
For the search method I use 'if str(query).upper() in id.upper()' in a list comprehension.
class Db:
def __init__(self):
self.items = {
'Picture1': {'name': 'name1', 'qty': 1},
'Picture2': {'name': 'name2', 'qty': 2},
'Picture3': {'name': 'name3', 'qty': 3}}
def search(self, query):
return [(id, self.items[id]['name'], self.items[id]['qty'])
for id in self.items if str(query).upper() in id.upper()]
db = Db()
db.search('pic')
db.search('ure2')
I want the user to input an item and a quantity and if the item is already stocked in the "database", which is my txt file, it add the quantity to the already existing item.
def item_list():
my_dict = dict()
add_item = input("Enter item name: ")
add_quantity = input("Enter quantity of {0} : ".format(add_item))
int_quantity = int(add_quantity)
my_dict[add_item] = int_quantity
with open("groceries.txt", "a") as text_file:
if add_item in my_dict.keys():
print("item {0} already exists".format(add_item))
addqte = my_dict[add_item]+ int_quantity
my_dict[add_item] = addqte
text_file.write(str(my_dict))
else :
text_file.write(str(my_dict))
print(" {0} {1} added .".format(add_quantity, add_item))
text_file.close()
show_list()
Actual result: says its already in the dict and just double the quantity (even if the dict was empty before the input) and create a new key
Expected result: Should write a new item and its quantity or if the item is already in the dict, add the quantity input but does not create another instance of that same item.
I feel like it takes my newly added item and says its already in the dict so it always go in the if section. Any idea on what to do next?
You need to load the data from the file into my_dict first. Then you update the dict with the new quantity, and finally you overwrite the entire file from the dict.
def item_list():
with open("groceries.txt", "r") as text_file:
my_dict = {item: int(quantity) for item, quantity in map(lambda line: line.split(), text_file)}
add_item = input("Enter item name: ")
add_quantity = input("Enter quantity of {0} : ".format(add_item))
int_quantity = int(add_quantity)
if add_item in my_dict:
print("item {0} already exists".format(add_item))
my_dict[add_item]+= int_quantity
else:
my_dict[add_item] = int_quantity
print(" {0} {1} added .".format(add_quantity, add_item))
with open("groceries.txt", "w") as text_file:
for item, quantity in my_dict.items():
text_file.write(f"{item} {quantity}\n")
I'm still relatively new to python, and this is probably way out of my ability, but I'm working on a program (For a school programming course) that asks for a new item, the price of that item, and the quantity of that item each time a loop goes around. (The loop will be stopped by typing stop when the program asks if there are more items to process) The program will then sends all those variables to a module I created that will calculate the total cost of each item based on the quantity, and then print out the cost of each item, and the total cost.
My teacher says this is possible, but he doesn't quite know how to do it.
Here's what I have so far (I tried to use a list, but it doesn't seem to be working out):
First Program (total_run.py):
import total_cost
itemname = []
itemprice = []
quantity = []
stop = "go"
while stop != "stop":
itemname.append(input("What is the name of the item?\n"))
itemprice.append(float(input("What is the price of the item?\n")))
quantity.append(float(input("How many of these items are there?\n")))
stop = input("Enter \"stop\" to add up the total")
name,price = total_cost.total(itemname,itemprice,quantity)
totalprice = total_cost.final(itemprice)
#Not sure how to print an unknown number of times
print(name," $",price)
print("Your total is: $", totalprice)
Second Program (total_cost.py):
#Calculates all the costs
itemprice = 0
def total(itemname,itemprice,quant):
itemprice = 0
itemname = itemname
for values in quant:
itemprice *= values
return itemname,itemprice
def final(itemprice):
finalcost = itemprice += itemprice
#I'm not sure on how to add up all the items in a list
return finalcost
Your data structures are wrong. Really you just want a single list of items, and each item in that list is itself a list (or a tuple) of name, price, quantity. Then you can simply add up the prices of each item in the list.
items = []
while stop != "stop":
name = input("What is the name of the item?\n")
price = float(input("What is the price of the item?\n"))
quantity = float(input("How many of these items are there?\n"))
items.append((name, price, quantity))
Now you can easily calculate the total per item, and the overall total:
overall_total = 0
for item in items:
total_price = item[1] * item[2]
overall_total += total_price
You can keep the lists in separately, and then iterate through them with a for loop like so:
costs = []
while stop != "stop":
itemname.append(input("What is the name of the item?\n"))
itemprice.append(float(input("What is the price of the item?\n")))
quantity.append(float(input("How many of these items are there?\n")))
stop = input("Enter \"stop\" to add up the total")
for i in range(len(itemname)):
costs.append(itemprice[i]*quantity[i])
total_cost = sum(costs)
Noteworthy things (can't comment, so part of answer here, sorry):
In total_cost.total, you define itemprice = 0 and then multiply by it itemprice *= values so itemprice will remain 0
You pass itemprice and itemname to the total_cost.total function, and then redefine itemprice = 0 and reassign itemname to itself (doesn't break the code though)
Strings in python can be defined by " or ', and the other will not stop the string. so my_string = "Hello, it's a nice day out" or stop = input('Enter "stop" to total the price up') will work.
You can print an unknown amount of items by iterating through the list with a for loop (as shown above
Cheers
As Daniel said, it's better to pack data about one item into one creature.
He suggests tuple, I suggest class:
class Item:
def __init__(self, name=None, price=None, quantity=None):
self.name, self.price, self.quantity = name, price, quantity
#classmethod
def ask_user(cls):
return cls(input('The name of Item: '), float(input('The price: ')), float(input('How much of Items you have: ')))
def value(self):
return self.price * self.quantinity
def total_value(items):
sum = 0
for i in items:
sum += i.value()
return sum
Also, instead of waiting for "stop", you can wait for End-Of-File
(Linux: Ctrl+D in empty line, Windows: Ctrl+Z, then Enter):
items = []
while True:
try:
items.append(Item.ask_user())
except EOFError: #no mire items to read
break #exit from the loop
except Exception as e: #other error
print(type(e), e) #print its type and the message
print(total_value(items))