Product Inventory project using pandas - python

Am trying to make a simple python program where we have to Create an application which manages an inventory of products.To create a product class which has a price, id, and quantity on hand. Then create an inventory class which keeps track of various products and can sum up the inventory value.
Please check the code below,
Input
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()
Output
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....
After i press 2, am expecting my program to give me value and tell me, 1)Would u like to add even more products?2)Get the inventory value3)ExitHow do i do that? Also if u find any modifications or any suggestions, please let me know down below.

I personally would remove the while true loop and create functions to accomplish your task:
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

Try this
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()

Related

Complete the Car class by creating an attribute purchase_price (type int) and the method print_info() that outputs the car's information

class Car:
def __init__(self):
self.model_year = 0
# TODO: Declare purchase_price attribute
self.purchase_price = 0
self.current_value = 0
def calc_current_value(self, current_year):
depreciation_rate = 0.15
# Car depreciation formula
car_age = current_year - self.model_year
self.current_value = round(self.purchase_price * (1 - depreciation_rate) ** car_age)
# TODO: Define print_info() method to output model_year, purchase_price, and current_value
if __name__ == "__main__":
year = int(input())
price = int(input())
current_year = int(input())
my_car = Car()
my_car.model_year = year
my_car.purchase_price = price
my_car.calc_current_value(current_year)
my_car.print_info()
def print_info(self):
print("Car's information:")
print(" Model year:", self.model_year)
print("Purchase price:", self.purchase_price)
good day, I'm supposed to complete the car class, above is my current code, I am not sure how to fix the issue I keep getting the following error: my_car.print_info()
AttributeError: 'Car' object has no attribute 'print_info'
I have tried the above code, and also tried with this
def print_info(self):
print("Car's information:")
print(" Model year:", self.model_year)
print("Purchase price:", self.purchase_price)
I keep getting the same error. I am a beginner at this stuff so please help me understand.
it seems like your function is outside of the class. notice how you have a #TODO-- this is where you want to insert the function and be mindful of indentations.
Otherwise, your print function is fine.
As stated in the comments:
class Car:
def __init__(self):
self.model_year = 0
# TODO: Declare purchase_price attribute
self.purchase_price = 0
self.current_value = 0
def calc_current_value(self, current_year):
depreciation_rate = 0.15
# Car depreciation formula
car_age = current_year - self.model_year
self.current_value = round(
self.purchase_price * (1 - depreciation_rate) ** car_age)
# TODO: Define print_info() method to output model_year, purchase_price, and current_value
def print_info(self):
print("Car's information:")
print(" Model year:", self.model_year)
print("Purchase price:", self.purchase_price)
if __name__ == "__main__":
year = int(input())
price = int(input())
current_year = int(input())
my_car = Car()
my_car.model_year = year
my_car.purchase_price = price
my_car.calc_current_value(current_year)
my_car.print_info()
Input:
1
1
1
Output:
Car's information:
Model year: 1
Purchase price: 1

Shopping Program not displaying results accurately

I am creating a program that lets a user choose an item to buy, specify how many units they want to purchase, adds the items to the users cart, and then gives a summary of the users cart when they are finished shopping.
I am currently having two problems:
I need to decrement the units available for purchase based on whatever quantity the user selects during checkout. For example, if the user purchases 2 shirts, the menu will print again and show that the units available decreased from 20 to 18.
In my cart summary, I am having trouble figuring out how to get the total price based on the quantity of whatever items the user chose.
I need to display they number of items left in the cart after the cart is cleared. I have tried using count() but received an AttributeError. Essentially, I just need to make sure the print statement looks like this "Number of items left in Cash Register: 0".
RetailItem class:
class RetailItem:
def __init__(self, description = '', units = 0, price = 0.0):
self.__description = description
self.__units = units
self.__price = price
def __str__(self):
displayString = (f'{"Descirption":10}{self.__desciption}\n'
f'{"Inventory":10}{self.__units:15}\n'
f'{"Price":10}{self.__price:<15.2f}\n')
return displayString
#property
def description(self):
return self.__description
#description.setter
def description(self, d):
self.__description = d
#property
def units(self):
return self.__units
#units.setter
def units(self, u):
self.__units = u
#property
def price(self):
return self.__price
#price.setter
def price(self, p):
self.__price = p
#property
def price(self):
return self.__price
#price.setter
def price(self, p):
self.__price = p
CashRegister class:
class CashRegister:
def __init__(self):
self.__item = []
def purchase_item(self, item):
self.__item.append(item)
def get_total(self):
total = 0.0
for item in self.__item:
total += (item.price * item.units)
return total
def show_items(self):
for item in self.__item:
print(f'{item.description}, units: {item.units}, price: {item.price}')
def clear(self):
for item in self.__item:
self.__item.remove(item)
def __str__(self):
return f'Listed Item: {self.__item}'
MakePurchase.py:
from RetailItem import RetailItem as ri
from CashRegister import CashRegister as cr
def showMenu():
jacket = ri('Jacket', 12, 59.95)
jeans = ri('Designer Jeans', 40, 34.95)
shirt = ri('Shirt', 20, 24.95)
register = cr()
choice = '1'
while choice != '0':
print('\n**Menu**')
print(f'{"Choice"}{"Description":>19} {"Price":>20} {"Stock":>21}')
print(f'{"======"}{"===========":>19} {"=====":>20} {"=====":>21}')
print(f'{"1"}{jacket.description:>19} {jacket.price:>25} {jacket.units:>18}')
print(f'{"2"}{jeans.description:>19} {jeans.price:>26} {jeans.units:>18}')
print(f'{"3"}{shirt.description:>19} {shirt.price:>26} {shirt.units:>18}')
print(f'{"======"}{"===========":>19} {"=====":>20} {"=====":>21}')
choice = input('Insert your choice or 0 to exit: ')
if choice == '0':
showCart(register)
elif choice == '1':
quantity = input('Insert quantity: ')
register.purchase_item(jacket)
elif choice == '2':
quantity = input('Insert quantity: ')
register.purchase_item(jeans)
elif choice == '3':
quantity = input('Insert quantity: ')
register.purchase_item(shirt)
else:
print('That item is not available')
def showCart(register):
print('\nCart')
print('====')
print(f'{register.show_items()}')
print('====')
print(f'Total Price: {register.get_total():.2f}')
print('============')
print('\nClearing cash register...')
print('\nNumber of items left in Cash Register: ',) #NEED TO GET NUMBER OF ITEAMS LEFT IN CART
print(register.clear())
def main():
showMenu()
if __name__ == '__main__':
main()
SAMPLE OUTPUT:
**Menu**
Choice Description Price Stock
====== =========== ===== =====
1 Jacket 59.95 12
2 Designer Jeans 34.95 40
3 Shirt 24.95 20
====== =========== ===== =====
Insert your choice or 0 to exit: 3
Insert quantity: 2
**Menu**
Choice Description Price Stock
====== =========== ===== =====
1 Jacket 59.95 12
2 Designer Jeans 34.95 40
3 Shirt 24.95 20
====== =========== ===== =====
Insert your choice or 0 to exit: 0
Cart
====
Shirt, units: 20, price: 24.95 #UNITS SHOULD BE 2
None #NOT SURE HOW TO PREVENT THIS FROM PRINTING
====
Total Price: 499.00 #SHOULD BE 49.90
============
Clearing cash register...
Number of items left in Cash Register: #SHOULD BE 0 INSTEAD OF NONE
None

How to store the total withdrawn amount for each category obejct? [duplicate]

I have a Category class and there is a ledger attribute for each instance of this class. This ledger attribute is actually a list of dictionaries which contain the withdrawal and deposit amounts and descriptions in the form {"amount" : amount, "description" : description}. Now, I want to define a function create_spend_chart which will take a list of objects as the parameter, and will find the total amount of withdrawals. I have been able to do this successfully:
def create_spend_chart(categories):
total_withdrawn = 0
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
total_withdrawn += -p["amount"]
But the problem I'm facing here is, I can't seem to store the total withdrawal amount for each category object separately. How can I do this?
My code-base might help you ins answering the question:
class Category:
def __init__(self, name):
self.name = name
self.ledger = list()
def get_balance(self):
total_balance = 0
for i in self.ledger:
total_balance += i["amount"]
return total_balance
def check_funds(self, amount):
if self.get_balance() >= amount:
return True
else:
return False
def deposit(self, amount, description = "Deposit"):
form = {"amount" : int(amount), "description" : description}
self.ledger.append(form)
def withdraw(self, amount, description = "Withdrawal"):
if description == None:
description = "Withdrawal"
form = {"amount" : -int(amount), "description" : description}
if self.check_funds(amount):
self.ledger.append(form)
return True
else:
return False
def transfer(self, amount, category_object):
form1 = {"amount" : -int(amount), "description" : f"Transfer to {category_object.name}"}
form2 = {"amount" : int(amount), "description" : f"Transfer from {self.name}"}
if self.check_funds(amount):
self.ledger.append(form1)
category_object.ledger.append(form2)
return True
else:
return False
def __repr__(self):
Ledger = ""
for i in self.ledger:
if len(i["description"]) > 23:
des = i["description"][:23]
else:
des = i["description"]
Ledger += des.ljust(23) + str(round(i["amount"], 2)).rjust(7) + "\n"
Ledger = Ledger + "Total: " + str(round(self.get_balance(), 2))
receipt = f"{self.name}".center(30, "*") + "\n" + Ledger
return receipt
def create_spend_chart(categories):
total_withdrawn = 0
withdrawals = list()
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
total_withdrawn += -p["amount"]
PS: This function is not a method, it is defined outside of the class declaration.
Use a collections.defaultdict to make aggregations such as that easy as pie.
import collections
# ...
withdrawn_per_category = collections.defaultdict(int)
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
withdrawn_per_category[i.name] += -p["amount"]
(I've opted to use int as the default data type, but it doesn't truly matter here, so long as it's a conversible numeric type.)
Without collections
If for some reason you don't want to use the handy, built-in collections module, you can emulate the same behavior yourself with a regular dict:
withdrawn_per_category = {}
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
withdrawn_per_category[i.name] = withdrawn_per_category.get(i.name, 0) - p["amount"]

Python Product Inventory

I'm working on a simple product inventory which essentially allows user to add products, display them and deduce the inventory value. I am stuck in the part where the inventory value is deduced. What I want the code to do here is multiply the product price * product quantity for each added product and return the sum. When I run the code, I get the error, TypeError: 'int' object is not iterable. I am new at Python, would appreciate any guidance!
Here is a portion of the code:
class Product:
def __init__(self, idnum, price, quantity):
self.idnum = idnum
self.price = price
self.quantity = quantity
class Inventory:
def __init__(self):
self.productlist = []
def add_product(self):
idnum = int(input('Enter id: '))
price = int(input('Enter price: '))
quantity = int(input('Enter quantity: '))
self.productlist.append(Product(idnum, price, quantity))
return self.productlist
def display(self):
for product in self.productlist:
print(product.idnum, product.price, product.quantity)
def inventory_value(self):
for product in self.productlist:
return sum(product.price*product.quantity)
I think you meant to sum all the products (the result of multiplication) like that:
def inventory_value(self):
running_sum = 0
for product in self.productlist:
running_sum += product.price * product.quantity
return running_sum
Or simply:
def inventory_value(self):
return sum(product.price * product.quantity for product in self.productlist)
Notice that this `sums over a collection, and not a single integer, like in your case:
>>> [x * (x + 1) for x in range(5)]
[0, 2, 6, 12, 20]
>>> sum(x * (x + 1) for x in range(5))
40

Search within a dictionary with a lot of values in python

In the following code I'm showing a function that lets you add students to a dictionary (book) with rut being the key, the issue I have is that I'm trying to make a function that can search by department and then print all students of that are part of that department, basically I'm asking how do you search a dictionary with 1 key that is associated to a lot of values and you want to search for a particular value and then print all keys that have it along with their info?
book = {}
def add(rut, name, age, department):
student = {}
student['rut'] = rut
student['name'] = name
student['age'] = age
student['department'] = department
book[rut] = student
def printall():
for rut in book:
student = book[rut]
print(student['rut'], student['name'], student['age'], student['department'])
def main():
count = 0
x = 0
y = int(input("How many students will you add?: "))
while count < y:
print('Input data of the student: ', count+1)
rut = input("rut: ")
name = input("name: ")
age = int(input("age: "))
print("Department 1: RH, 2: Logistic, 3: Cleaners, 4: TI ")
department = ''
while x == 0:
num_dept = int(input("department number: "))
if num_dept == 1:
department = "RH"
x = 1
elif num_dept == 2:
department = "Logistic"
x = 1
elif num_dept == 3:
department = "Mathematics"
x = 1
elif num_dept == 4:
department = "TI"
x = 1
else:
print('Error')
x = 0
add(rut, name, age, department)
count = count + 1
printall()
main()
You can use a list comprehension.
students = [student for student in book.values()
if student["department"] == desired_department]
This will give you a list, which you can then print out if you so choose.

Categories