Python 如何减去库存中的项目,并在以后的程序中打印它们?

Python 如何减去库存中的项目,并在以后的程序中打印它们?,python,Python,我有一个完全可以工作的程序,除了我必须让它报告在用户“结帐”(选项2)后库存中还有多少物品。我创建了一个名为inhand的函数。在这个函数中,我为库存中的每个项目分配了100个数量。假设下一行取用户选择的项目并减去他们输入的数量。用户选择选项2“签出”后。它打印一张“账单”。我想让它打印出每件商品的库存量。相反,它当前会出错。我该如何解决这个问题 完整代码: #DEFINING EACH RETAIL ITEM TEMPLATE class RetailItem: def __init

我有一个完全可以工作的程序,除了我必须让它报告在用户“结帐”(选项2)后库存中还有多少物品。我创建了一个名为inhand的函数。在这个函数中,我为库存中的每个项目分配了100个数量。假设下一行取用户选择的项目并减去他们输入的数量。用户选择选项2“签出”后。它打印一张“账单”。我想让它打印出每件商品的库存量。相反,它当前会出错。我该如何解决这个问题

完整代码:

#DEFINING EACH RETAIL ITEM TEMPLATE

class RetailItem:
    def __init__(self,desc,unit,price):
        self.description = desc
        self.units = unit
        self.price = price

#CREATING WHERE SELECTED ITEMS WITH RESIDE
class CashRegister:
    def __init__(self):
        self.shopping_list=[]
    def purchase_item(self,retail):
        #adding item to list
        self.shopping_list.append(retail)
#CREATING PRICING / COST
    def get_total(self):
        total = 0
        for i in self.shopping_list:
            total+=(i.units*i.price)
        return total
#HOW THE CHECKOUT WILL FORMAT/LOOK IN AFFECT ON OPTION 2 (CHECKOUT)
    def show_items(self):
        if not self.shopping_list:
            return
        print("{:<15}{:<25}{:<25}{:<10}".format(" "*9,"Description","Units","Price"))
        print("-"*75)
        for c,i in enumerate(self.shopping_list,1):
            print("{:<15}{:<25}{:<25}{:<10}".format("Item #"+str(c),i.description,i.units,i.price))
        print("-"*75)

    def inhand():
        inventory = { "Pants":100, "Shirt":100, "Dress":100, "Socks":100, "Sweater":100 }
        inventory[item_type] -= qty_purchased
        
def main():
    #ADDING TO CART
    c=CashRegister()
    #MENU
    
    while 1:
        try:
            print("1. Purchase\n2. Checkout\n3. Clear\n4. Exit")
            print()
            choice = int(input("Enter your choice: "))
            print()
            if choice == 1:
                while 1:
                    print()
                    print("Menu\n-----------------------\n1. Pants\n2. Shirt\n3. Dress\n4. Socks\n5. Sweater")
                    item_type = int(input("Select item: "))
                    print()
                    qty=int(input("Enter quantity: "))
                    #ITEMS TO CHOOSE FROM AND ADD TO CART
                    if item_type == 1:
                        c.purchase_item(RetailItem("Pants",qty,44.95))
                    elif item_type == 2:
                        c.purchase_item(RetailItem("Shirt",qty,34.95))
                    elif item_type == 3:
                        c.purchase_item(RetailItem("Dress",qty,79.95))
                    elif item_type == 4:
                        c.purchase_item(RetailItem("Socks",qty,6.95))
                    elif item_type == 5:
                        c.purchase_item(RetailItem("Sweater",qty,24.95))
                    else:
                        #ERROR MESSAGE
                        print("Invalid item! try again")
                        print()
                        continue
                    print("Item added to list")
                    print()
                    break
            elif choice == 2:
                if not c.shopping_list:
                    #ERROR MESSAGE
                    print("Nothing to checkout!")
                    print()
                    continue
                #DISPLAYING BILL
                c.show_items()
                print(" "*60+"Total: ${}".format(round(c.get_total(),2)))
                print()
                print(inhand)
            elif choice == 3:
                #CLEARING
                c.shopping_list=[]
            elif choice == 4:
                #EXIT
                exit()
            else:
                #ERROR MESSAGE
                print("Invalid choice! try again!")
            print()
            #ERROR MESSAGE
        except Exception as e:
            print("Invalid choice! try again!"+str(e))
            print()

#RUN PROGRAM
if __name__ == "__main__":
    main()
#定义每个零售商品模板
类别零售项目:
定义初始(自我、描述、单位、价格):
self.description=desc
self.units=单位
self.price=价格
#创建包含选定项目的位置
类别收银机:
定义初始化(自):
self.shopping_list=[]
def采购项目(自有、零售):
#将项目添加到列表中
self.shopping\u list.append(零售)
#创建定价/成本
def get_总计(自身):
总数=0
对于self.shopping_列表中的i:
总计+=(i.单位*i.价格)
返回总数
#签出的格式/外观如何影响选项2(签出)
def显示_项(自身):
如果不是自助购物清单:
返回

打印(“{:您必须首先声明
inhand
函数作用域变量,并使函数在整个类中可访问,然后将
inventory
分配给类变量,否则它将不会全局存储在类中(仅在函数内部),例如:

def inhand(self,item_type,qty_purchased):
    self.inventory = { "Pants":100, "Shirt":100, "Dress":100, "Socks":100, "Sweater":100 }
    self.inventory[item_type] -= qty_purchased
这样,您就可以使用for循环重复使用它

self.item_type_qty[["Pants",20],["Dress",20]] #for example, this variable store user picked item
for x in self.item_type_qty:
    self.inhand(x[0],x[1]) #calling inhand function repetitively

您还需要验证这些库存值是否低于零。此时您可以自己计算出来。祝您好运

在构造函数中初始化库存。让
inhand
函数检查库存,如果可以购买,则返回True\False

请尝试以下代码:

#CREATING WHERE SELECTED ITEMS WITH RESIDE
class CashRegister:
    def __init__(self):
        self.shopping_list=[]
        self.inventory = { "Pants":100, "Shirt":100, "Dress":100, "Socks":100, "Sweater":100 }
        
    def purchase_item(self,retail):
        #adding item to list
        if self.inhand(retail.description, retail.units):
           self.shopping_list.append(retail)
        
#CREATING PRICING / COST
    def get_total(self):
        total = 0
        for i in self.shopping_list:
            total+=(i.units*i.price)
        return total
#HOW THE CHECKOUT WILL FORMAT/LOOK IN AFFECT ON OPTION 2 (CHECKOUT)
    def show_items(self):
        if not self.shopping_list:
            return
        print("{:<15}{:<25}{:<25}{:<10}".format(" "*9,"Description","Units","Price"))
        print("-"*75)
        for c,i in enumerate(self.shopping_list,1):
            print("{:<15}{:<25}{:<25}{:<10}".format("Item #"+str(c),i.description,i.units,i.price))
        print("-"*75)
        
    def inhand(self,item_type,qty_purchased):
        if self.inventory[item_type] < qty_purchased:
           print(f"Cannot purchase {qty_purchased} {item_type}. Only {self.inventory[item_type]} left in stock.")
           return False
        self.inventory[item_type] -= qty_purchased
        return True

如果您遇到错误,请将您的问题包括完整的错误回溯,因为这将告诉您错误发生的位置您没有在`库存[项目类型]-=购买数量'中声明项目类型和购买数量,我没有这样做。-1来自我。您最好这样做。
 #DISPLAYING BILL
 c.show_items()
 print(" "*60+"Total: ${}".format(round(c.get_total(),2)))
 print()
 print(">> Inventory:", c.inventory)