Инвентаризация проекта с использованием pandas - PullRequest
0 голосов
/ 09 апреля 2020


Я пытаюсь создать простую python программу, в которой нам нужно создать приложение, которое управляет инвентаризацией продуктов. Создать класс продукта, у которого есть цена, идентификатор и количество под рукой. Затем создайте класс инвентаря, который отслеживает различные продукты и может суммировать стоимость инвентаря.

Пожалуйста, проверьте код ниже,

Ввод

import pandas as pd

class Product:
    def __init__(self):
        self.price = None
        self.id = None
        self.qty = None
        self.data = pd.DataFrame(([]),columns=['ID','Cost','Quantity'])
class inventory(Product):
        def value(self):
            while True:
                    print("Please give your product details,")
                    self.cost = float(input("Cost of the product : "))
                    self.id = int(input("ID of the product : "))
                    self.qty = int(input("Quantity of the product : "))
                    print("==============================================================================")
                    self.data = self.data.append({'ID':self.id,'Cost':self.cost,'Quantity':self.qty},ignore_index=True)
                    print(self.data)
                    print("==============================================================================")
                    print("1)Would u like to add even more products?\n2)Get the inventory value\n3)Exit")
                    option = int(input())
                    if(option == 1):
                        inventory.value(self)
                    elif(option==2):
                        print("The total value of inventory is : ",((self.data['Cost'])*(self.data['Quantity'])).sum())
                    else:
                        print("Exiting....")
                        exit()
                        break
            return


inv = inventory()
inv.value()



Выход

Please give your product details,                                                                                                                              
Cost of the product : 10                                                                                                                                       
ID of the product : 11                                                                                                                                         
Quantity of the product : 12                                                                                                                                   
==============================================================================                                                                                 
     ID  Cost  Quantity                                                                                                                                        
0  11.0  10.0      12.0                                                                                                                                        
==============================================================================                                                                                 
1)Would u like to add even more products?                                                                                                                      
2)Get the inventory value                                                                                                                                      
3)Exit                                                                                                                                                         
2                                                                                                                                                              
The total value of inventory is :  120.0                                                                                                                       
Please give your product details,                                                                                                                              
Cost of the product : 12                                                                                                                                       
ID of the product : 12                                                                                                                                         
Quantity of the product : 12                                                                                                                                   
==============================================================================                                                                                 
     ID  Cost  Quantity                                                                                                                                        
0  11.0  10.0      12.0                                                                                                                                        
1  12.0  12.0      12.0                                                                                                                                        
==============================================================================                                                                                 
1)Would u like to add even more products?                                                                                                                      
2)Get the inventory value                                                                                                                                      
3)Exit                                                                                                                                                         
3                                                                                                                                                              
Exiting....  


После того, как я нажму 2, я ожидаю, что моя программа даст мне значение и скажет мне, 1) Хотели бы вы добавить еще больше продуктов? 2) Получить стоимость инвентаря3) Выход

Как мне это сделать? Также, если вы найдете какие-либо изменения или предложения, пожалуйста, дайте мне знать ниже.

Ответы [ 2 ]

0 голосов
/ 09 апреля 2020

Я бы лично удалил истинное l oop и создал бы функции для выполнения sh вашей задачи:

import pandas as pd

class Product(object):
    def __init__(self):
        self.price = None
        self.id = None
        self.qty = None
        self.data = pd.DataFrame(([]),columns=['ID','Cost','Quantity'])

class inventory(Product):
    # create a prod_detail function
    def prod_detail(self):
        print("Please give your product details,")
        self.cost = float(input("Cost of the product : "))
        self.id = int(input("ID of the product : "))
        self.qty = int(input("Quantity of the product : "))
        print("="*30)
        self.data = self.data.append({'ID':self.id,'Cost':self.cost,'Quantity':self.qty},ignore_index=True)
        print(self.data)
        print("="*30)
        self.option()
    # create an options function
    def option(self):
        print("1)Would u like to add even more products?\n2)Get the inventory value\n3)Exit")
        option = int(input())
        if(option == 1):
            self.prod_detail()
        elif(option==2):
            print("The total value of inventory is : ",((self.data['Cost'])*(self.data['Quantity'])).sum())
            self.option()
        else:
            print("Exiting....")
            exit()

    def value(self):
        # remove the while true loop and just run the prod_detail function
        self.prod_detail()


inv = inventory()
inv.value()

Please give your product details,
Cost of the product :  1
ID of the product :  2
Quantity of the product :  3
==============================
    ID  Cost  Quantity
0  2.0   1.0       3.0
==============================
1)Would u like to add even more products?
2)Get the inventory value
3)Exit
 2 <--------
The total value of inventory is :  3.0
1)Would u like to add even more products?
2)Get the inventory value
3)Exit
0 голосов
/ 09 апреля 2020

Попробуйте это

import pandas as pd

class Product:
    def __init__(self):
        self.price = None
        self.id = None
        self.qty = None
        self.data = pd.DataFrame(([]),columns=['ID','Cost','Quantity'])
class inventory(Product):
    def value(self):
        while True:
            option = 1
            if len(self.data):
                print("1)Would u like to add even more products?\n2)Get the inventory value\n3)Exit")
                option = int(input())
            if option == 1:
                print("Please give your product details,")
                self.cost = float(input("Cost of the product : "))
                self.id = int(input("ID of the product : "))
                self.qty = int(input("Quantity of the product : "))
                print("==============================================================================")
                self.data = self.data.append({'ID':self.id,'Cost':self.cost,'Quantity':self.qty},ignore_index=True)
                print(self.data)
                print("==============================================================================")
                inventory.value(self)
            elif option == 2:
                print("The total value of inventory is : ",((self.data['Cost'])*(self.data['Quantity'])).sum())
            else:
                print("Exiting....")
                exit()

inv = inventory()
inv.value()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...