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
Related
The program offers items, has the user pay for items, 'gives' the items. It seems to work more or less. I have 2 questions:
I don't know how to deduct the cash from cash it is deposited and when they select the item, it should detect the cash from the deposit and give back the rest of the changes
Is there a way to make the code simpler/better?
import time
import sys
class CashBox(object):
def __init__(self):
self.credit = 0
self.totalReceived = 0
#self.price = 35
def deposit(self, amount):
self.credit = amount + self.credit
self.totalReceived = amount + self.totalReceived
print("Depositing {0} cents. You have {1} cents credit.".format(
amount, self.credit))
# print(type(self.credit))
return self.credit
def returnCoins(self):
print("Returning ", self.credit/100, " dollars.")
self.totalReceived = 0
def haveYou(self, name, price, recipe):
return self.credit >= price
def deduct(self, amount):
pass
def totalCoins(self):
return self.totalReceived
class CoffeeMachine(object):
def __init__(self):
self.cashBox = CashBox()
self.credit = CashBox.__init__
self.selector = self.cashBox
def oneAction(self):
while True:
command = input("""
______________________________________________________
PRODUCT LIST: all 35 cents, except bouillon (25 cents)
1=black, 2=white, 3=sweet, 4=sweet & white, 5=bouillon
Sample Commands: insert 25, select 1, cancel, quit.
Your command:
""")
words = command.lower().split()
if 'select' in words:
Selector.select(self, int(words[1]))
elif 'insert' in words:
coinsAllowed = [5, 10, 25, 50]
if int(words[1]) in coinsAllowed:
self.cashBox.deposit(int(words[1]))
else:
print(
"""We only take half-dollars, quarters, dimes, and nickels.""")
elif 'cancel' in words:
print("Cancelling transaction. Returning to main menu: ")
self.cashBox.returnCoins()
elif 'quit' in words:
break
else:
print("Invalid command.")
def totalCash(self):
return self.cashBox.totalReceived
class Product(object):
def __init__(self, name, price, recipe):
self.name = name
self.price = price
self.recipe = recipe
def getPrice(self):
return self.price
def make(self):
for item in self.recipe:
print("dispensing", item)
time.sleep(0.5)
print("Enjoy your", self.name)
time.sleep(0.5)
# print(self.price)
class Selector(object):
def __init__(self):
#self.Product = Product()
self.cashBox = CashBox()
self.credit = CashBox.deposit
# self.products.append(Product.
def select(self, choiceIndex):
recipes = {
1: ["Black coffee", 35, ["cup", "coffee", "water"]],
2: ["White coffee", 35, ["cup", "coffee", "creamer", "water"]],
3: ["Sweet coffee", 35, ["cup", "coffee", "sugar", "water"]],
4: ["White & Sweet coffee", 35, ["cup", "coffee", "sugar", "creamer", "water"]],
5: ["Bouillon", 25, ["cup bouillonPowder", "water"]]
}
if choiceIndex in range(1, len(recipes)+1):
self.choiceIndex = choiceIndex
self.recipe = recipes.get(choiceIndex)
product = Product(*self.recipe)
if self.cashBox.haveYou(*self.recipe) == True:
#print(self.recipe,"Great selection")
#price = CashBox.haveYou(*self.recipe)
product.make()
self.cashBox.haveYou = self.cashBox.haveYou - self.cashBox.deduct
print("Returning {0} cents.".format(self.cashBox.haveYou))
else:
print("Sorry. Not enough money deposited.")
else:
print("That selection does not exist")
def main():
m = CoffeeMachine()
while m.oneAction():
pass
total = m.totalCash()
print(f"Total cash received: ${total/100:.2f}")
if __name__ == "__main__":
main()
So I've been making a simple program where you can select cars and buy/sell them, and they get stored in the inventory. Additionally, you can ask for specific attributes of what you want in your car. The code is as followed:
class Consumer:
#create an inventory to store cars
garage = []
def __init__(self, budget):
self.budget = budget
#returns current budget of user
def checkBudget(self):
return self.budget
#take money away from the budget and store the car in the inventory
def buy(self, car):
self.budget = self.budget - car.price
self.garage.append(car)
def sell(self, value):
#takes back original money and takes out car
self.budget = self.budget + self.garage[value].getPrice()
return self.garage.pop(value)
def showGarage(self):
for i in self.garage:
print(i.getInfo())
def carCount(self):
return len(self.garage) - 1
class Car:
def __init__(self, model, color, price, year):
self.model = model
self.color = color
self.price = price
self.year = year
def getName(self):
return ("{} {} from {}".format(self.color, self.model, self.year))
def getInfo(self):
return ("{} {} from {} that costs ${}".format(self.color, self.model, self.year, self.price))
def getColor(self):
return self.color
def getYear(self):
return self.year
def getPrice(self):
return self.price
class Sedan(Car):
def __init__(self, model, color, price, year):
super().__init__(model, color, price, year)
def colorPrice(self, color):
self.color = color
self.price = self.price + 200
class SUV(Car):
def __init__(self, model, color, price, year):
super().__init__(model, color, price, year)
def colorPrice(self, color):
self.color = color
self.price = self.price + 300
class Sports(Car):
def __init__(self, model, color, price, year):
super().__init__(model, color, price, year)
def colorPrice(self, color):
self.color = color
self.price = self.price + 800
class Bike(Car):
def __init__(self, model, color, price, year):
super().__init__(model, color, price, year)
def colorPrice(self, color):
self.color = color
self.price = self.price + 400
class Catalogue:
#placeholder to store all cars
whole = []
#sets user-defined preferences of cars
preferences = []
def __init__(self):
pass
def addCars(self, car):
self.whole.append(car)
self.preferences.append(car)
#shortens list so that the catalogue shows only the cars from the year the user wants from
def year(self, year):
for i in self.preferences:
if int(i.getYear()) != int(year):
self.preferences.remove(i)
if not self.preferences:
print("There are no cars from this year")
self.Reset()
print(self.preferences)
#shortens list so that the catalogue shows only the cars of a certain color
def color(self, color):
for i in self.preferences:
if str(i.getColor()) != str(color):
self.preferences.remove(i)
if not self.preferences:
print("There are no cars of this color")
self.Reset()
print(self.preferences)
#shortens list so that it only shows the price range
def price(self, low, high):
for i in self.preferences:
if int(i.getPrice()) <= int(low) or int(i.getPrice()) >= int(high):
self.preferences.remove(i)
if not self.preferences:
print("There are no cars from this price range")
self.reset()
#clears all preferences so that it shows all available cars
def Reset(self):
self.preferences.clear()
for i in self.whole:
self.preferences.append(i);
def showCatalogue(self):
for i in range(len(self.preferences)):
print(self.preferences[i].getInfo())
def getLength(self):
return len(self.preferences)
#gives the car away
def sell(self, value):
self.whole.pop(value)
a = self.preferences.pop(value)
return a
showcase = Catalogue()
Toyota = Sedan('Toyota Camry', 'blue', 64000, 2002)
Honda = Sedan('Honda Civic', 'red', 65000, 2002)
Dodge = SUV('Dodge Durango', 'black', 4324, 2015)
Yamaha = Bike('Yamaha x', 'red', 23240, 2015)
showcase.addCars(Toyota)
showcase.addCars(Honda)
showcase.addCars(Dodge)
showcase.addCars(Yamaha)
customer = Consumer(100000)
#garage module
def garage():
global customer
global showcase
a = input("What do you want to do? 1) check car collection 2) sell car 3) back ")
#shows all cars from the inventory
if int(a) == 1:
customer.showGarage()
garage()
#sells available cars
elif int(a) == 2:
customer.showGarage()
#will cancel if there care no cars in the inventory
if len(customer.garage) == 0:
print("You have no cars")
garage()
else:
#enter index no to select a car
b = input("Pick a car from 0 to {} ".format(customer.carCount()))
if int(b) > int(customer.carCount()):
print("You don't have that many cars!")
garage()
else:
c = input("Are you sure you want to sell this car? 1) yes 2) no ")
#asks for warning confirmation
if int(c) == 1:
d = customer.sell(int(b))
showcase.addCars(d)
print("This car has been sold; have a nice day!")
garage()
elif int(c) == 2:
garage()
#go back to main
elif int(a) == 3:
e = input("Are you sure you wanna go back? 1) yes 2) no ")
if int(e) == 1:
main()
elif int(e) == 2:
garage()
#asks if you want to specify the list
def access():
global showcase
showcase.showCatalogue()
print()
g = input("Looking for specifics? 1) yes 2) no: ")
if int(g) == 1:
options()
else:
choose()
print()
#would you like to access catalogue or garage?
def main():
a = input("Where do you want to go next? 1) check garage 2) browse more cars" )
if int(a) == 1:
garage()
elif int(a) == 2:
access()
else:
print("Try again")
main()
#car purchase confirmation
def buy(car):
global customer
global showcase
a = input("Are you sure you want to buy this car? 1) yes 2) no " )
if int(a) == 1:
#cancels purchase automatically if your balance is low
if int(customer.checkBudget()) < int(showcase.preferences[car].getPrice()):
print("You do not have enough money")
access()
else:
#takes the car out of the catalogue and stores it in the garage
print("Transaction taking place...")
sold = showcase.sell(car)
customer.buy(sold)
print("You purchased this car")
print("You now have a budget of {} dollars".format(customer.checkBudget()))
main()
def choose():
#which car you would like to purchase
global showcase
c = input("Which car would you like? enter from 0 to {} ".format(showcase.getLength()-1))
if int(c) > int(showcase.getLength()):
print("Out of bounds, please try again")
choose()
else:
buy(int(c))
def options():
#which specifics are you looking for?
global showcase
a = input("What are you looking for? 1) color 2) price 3) year: 4) reset ")
if int(a) == 1:
b = input("Pick a color: ")
showcase.color(b)
elif int(a) == 2:
b = input("Pick a lower price range: ")
c = input("Pick an upper price range: ")
if showcase.price(b) > showcase.price(c):
print("Invalid Error")
else:
showcase.price(b,c)
elif int(a) == 3:
b = input("Pick a year: ")
showcase.year(b)
elif int(a) == 4:
showcase.Reset()
else:
print("Invalid, try again")
options();
access()
access()
My main issue is with the specifics. For example, when I type for a blue car, it gives me a black car. When I type for a car from 2015, it gives me a car from 2002. When I ask for a car no more than $50000, it gives me a car worth $65000. Here are some runtime scenarios:
What are you looking for? 1) color 2) price 3) year: 4) reset #1
Pick a color: #blue
#returns
blue Toyota Camry from 2002 that costs $64000
black Dodge Durango from 2015 that costs $4324
What are you looking for? 1) color 2) price 3) year: 4) reset #3
Pick a year: #2015
#returns
red Honda Civic from 2002 that costs $65000
black Dodge Durango from 2015 that costs $4324
red Yamaha x from 2015 that costs $23240
The code problem can be found here:
#shortens list so that the catalogue shows only the cars of a certain color
def color(self, color):
for i in self.preferences:
if str(i.getColor()) != str(color):
self.preferences.remove(i)
if not self.preferences:
print("There are no cars of this color")
self.Reset()
print(self.preferences)
#shortens list so that it only shows the price range
def price(self, low, high):
for i in self.preferences:
if int(i.getPrice()) <= int(low) or int(i.getPrice()) >= int(high):
self.preferences.remove(i)
if not self.preferences:
print("There are no cars from this price range")
self.reset()
The problem is, you are trying to remove items from a list which is being looped through. This may create unexpected behavior. Store the values to be removed and then later remove from the list, something like this
def color(self, color):
tobeRemoved = []
for i in self.preferences:
if str(i.getColor()) != str(color):
tobeRemoved.append(i)
for pref in tobeRemoved:
self.preferences.remove(pref)
if not self.preferences:
print("There are no cars of this color")
self.Reset()
print(self.preferences)
I was able to get the output you wanted
blue Toyota Camry from 2002 that costs $64000
red Honda Civic from 2002 that costs $65000
black Dodge Durango from 2015 that costs $4324
red Yamaha x from 2015 that costs $23240
Looking for specifics? 1) yes 2) no: 1
What are you looking for? 1) color 2) price 3) year: 4) reset 1
Pick a color: blue
blue Toyota Camry from 2002 that costs $64000
Looking for specifics? 1) yes 2) no:
You can do the same for price() also
I have a problem which is a simplified version of the knapsack problem. It goes like this. There is a store and we have a list of items in that store. Let's say like this,
Store has 2 types of products Normal products and limited products.
Product Class
class Product:
"""
A class to provide abstraction for products availabel in the system.
unless the product is a Limited_product its supply is infinite
"""
product_counter = 0
##### Part 1.1 #####
def __init__(self, name, price):
""" Constructor for initialization """
self.name = name
self.price = price
self.id = Product.product_counter
Product.product_counter += 1
def __str__(self):
""" returns a string representation of a product """
return "<{}> {} - {}$".format(self.id, self.name, self.price)
def __repr__(self):
""" represents the class object as a string """
return "PRODUCT <{}>".format(self.id)
Limited Product Class
class Limited_Product(Product):
"""
A child class of the parent Product class
Represents a Limited product where the quantity is depreceating
"""
##### Part 1.2 #####
def __init__(self, name, price, amount):
""" Constructor for initialization """
super().__init__(name, price)
self.amount = amount
def __str__(self):
""" returns a string representation of a limited product """
return "<{}> {} - {}$ ({} left)".format(self.id, self.name, self.price, self.amount)
def decrement_amount(self):
""" decrement the amount of available product """
self.amount -= 1
def get_amount(self):
""" returns the amount available from the product """
return self.amount
Now we are given a list of products and the maximum amount a customer can spend.
============================
Product - Price
A - 20$
B - 7$
C - 1$ (2 left)
============================
And we have to find out what is the minimum amount left after the customer buys a sequence from these items using both recursion as well as iteratively by completing the given two functions. These functions are given so I cannot write in a different method.
As an example:
>>> store.so_rich(45)
output - 1
You have 45 dollars to spend. The optimal solution is buying six B items and two C items. This will leave you with 45 - 7 * 6 - 1 * 2 = 1 dollars left. The least amount of money left is 1 since there is no way to spend all of the money. (although C’s price is 1$, you have purchased all of them already!)
>>> store.so_rich(61)
0
You have 61 dollars to spend. You can spend all of them by buying two A and three B (20 * 2 + 7 * 3 = 61). So the least amount of money left is 0.
The two functions that I wrote
def so_rich(self, money):
# suppose you haven't seen any product yet
# the only possible amount of money left is "money"
# this is a set to record the possible money left
left = set([money])
# get products
lst = list(self.warehouse.inventory.values())
print(str(lst))
for product in lst:
# a temporary set to save the updates of "left"
# you don't want to modify the set you're iterating through
tmp_left = set()
for m in left:
# update tmp_left
if type(product) != Limited_Product:
new_left = m
#new_left -= product.price
while product.price <= new_left:
print(new_left, product.name)
tmp_left.add(new_left)
new_left = new_left - product.price
else:
# handle limited product
new_left = m
product_count = product.amount
while product.price <= new_left and product_count > 0:
print(new_left, product.name)
tmp_left.add(new_left)
new_left = new_left - product.price
product_count -= 1
left = tmp_left
print(left)
return min(left)
def so_rich_recursive(self, money):
# get products
lst = list(self.warehouse.inventory.values())
def helper(lst, money):
# base case
if not lst:
return money
cur_min = money
product = lst[0]
if type(product) != Limited_Product:
tmp = money
while product.price < tmp:
cur_min = tmp
tmp -= product.price
print(cur_min, product.name)
else:
tmp = money
product_count = product.amount
while product.price <= tmp and product_count > 0:
cur_min = tmp
tmp -= product.price
product_count -= 1
print(cur_min, product.name)
money = money - cur_min
print("-----", money)
lst.pop(0)
return helper(lst, money)
return helper(lst, money)
I cannot understand why the above code written by me does not work. Can anyone help me, please?
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()
I have a code that reads an inventory txt file that is suppose to display a menu for the user when it is run. However, when it runs the quantity and pice columns are misaligned:
Select an item ID to purchase or return:
ID Item Quantity Price
244 Large Cake Pan 7.00 19.99
576 Assorted Sprinkles 3.00 12.89
212 Deluxe Icing Set 6.00 37.97
827 Yellow Cake Mix 3.00 1.99
194 Cupcake Display Board 2.00 27.99
285 Bakery Boxes 7.00 8.59
736 Mixer 5.00 136.94
Enter another item ID or 0 to stop
Here is my code:
import InventoryFile
def readFile ():
#open the file and read the lines
inventoryFile = open ('Inventory.txt', 'r')
raw_data = inventoryFile.readlines ()
#remove the new line characters
clean_data = []
for item in raw_data:
clean_item = item.rstrip ('\n')
clean_data.append (clean_item)
#read lists into objects
all_objects = []
for i in range (0, len(clean_data), 4):
ID = clean_data [i]
item = clean_data [i+1]
qty = float (clean_data [i+2])
price = float (clean_data [i+3])
inventory_object = InventoryFile.Inventory (ID, item, qty, price)
all_objects.append (inventory_object)
return all_objects
def printMenu (all_data):
print ()
print ('Select an item ID to purchase or return: ')
print ()
print ('ID\tItem\t\t Quantity\t Price')
for item in all_data:
print (item)
print ()
print ('Enter another item ID or 0 to stop')
def main ():
all_items = readFile ()
printMenu (all_items)
main ()
How can I format the output so that the quantity and price columns are correctly aligned?
Here is the inventory class:
class Inventory:
def __init__ (self, new_id, new_name, new_stock, new_price):
self.__id = new_id
self.__name = new_name
self.__stock = new_stock
self.__price = new_price
def get_id (self):
return self.__id
def get_name (self):
return self.__name
def get_stock (self):
return self.__stock
def get_price (self):
return self.__price
def restock (self, new_stock):
if new_stock < 0:
print ('ERROR')
return False
else:
self.__stock = self.__stock + new_stock
return True
def purchase (self, purch_qty):
if (new_stock - purch_qty < 0):
print ('ERROR')
return False
else:
self.__stock = self.__stock + purch_qty
return True
def __str__ (self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__stock, '7.2f') + format (self.__price, '7.2f')
Using your class Inventory's getters you can make a list and just join the output.
def printMenu (all_data):
print ()
print ('Select an item ID to purchase or return: ')
print ()
print ('ID\tItem\t\t Quantity\t Price')
for item in all_data:
product_id = item.get_id()
product_name = item.get_name()
product_stock = item.get_stock()
product_price = item.get_price()
output = [product_id, product_name, product_stock, product_price]
output = [str(item) for item in output]
print('{:<5}\t{:<5}\t{:<5}\t{:<5}'.format(output))
print ()
print ('Enter another item ID or 0 to stop')