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')
Related
To give you some background info, I basically have to create 2 classes called ItemToPurchase that contains an item's name, quantity, description, and price. The other class ShoppingCart adds the item's name into a list with some other functions that modify the list. The part where I am facing some issues is at the part of execute_menu(). Let's say I enter the option 'a', after I give all the details of the item, the entire program ends. I do not want that. I want the program to ask me for the next option and keep asking me the next option after I complete a specific letter's required details.
class ItemToPurchase:
def __init__(self):
self.name = 'none'
self.quantity = 0
self.price = 0
self.description = 'none'
def item_name(self, name):
self.name = name
def item_price(self, price):
self.price = price
def item_quantity(self, quantity):
self.quantity = quantity
def item_description(self, description):
self.description = description
def print_item_cost(self):
print(self.name + " " + str(self.quantity) + " # $" + str(self.price) + " = $" + str(int(self.quantity) * int(self.price)))
def print_item_description(self):
print(self.name + ": " + self.description)
class ShoppingCart:
def __init__(self, name='none', date='January 1, 2016'):
self.customer_name = name
self.current_date = date
self.cart_items = []
def add_item(self, New_cart):
self.cart_items.append(New_cart)
def remove_item(self, item_name):
count = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
if item.name == item_name:
del self.cart_items[i]
count += 1
if count == 0:
print()
print('Item not found in cart. Nothing removed')
def modify_item(self, ItemToPurchase, Item_Name):
num = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
if Item_Name in [x.name for x in items]:
num += 1
if ItemToPurchase.description != "none":
item.item_description(ItemToPurchase.description)
if ItemToPurchase.price != 0:
item.item_price(ItemToPurchase.price)
if ItemToPurchase.quantity != 0:
item.item_quantity(ItemToPurchase.quantity)
if num == 0:
print()
print('Item not found in cart. Nothing modified.')
print()
def get_num_items_in_cart(self):
total_number = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
total_number += item.quantity
return total_number
def get_cost_of_cart(self):
total_cost = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
total_cost += int(item.quantity*item.price)
return total_cost
def print_total(self):
print(self.customer_name + "'s Shopping Cart - " + str(self.current_date))
count = len(self.cart_items) + 1
if len(self.cart_items) > 0:
print('Number of items:' + str(count))
print()
for i in self.cart_items:
i.print_item_cost()
total = self.get_cost_of_cart()
print()
print('Total:', str(total))
else:
print('SHOPPING CART IS EMPTY')
def print_descriptions(self):
if len(self.cart_items) > 0:
print(self.customer_name + "'s Shopping Cart - " + str(self.current_date))
print()
print('Item Descriptions')
for j in self.cart_items:
j.print_item_description()
else:
print('SHOPPING CART IS EMPTY')
def print_menu(cart):
print('MENU')
print('a - Add item to cart')
print('r - Remove item from cart')
print('c - Change item quantity')
print("i - Output items' descriptions")
print('o - Output shopping cart')
print('q - Quit')
**def execute_menu(option, Cart):
while option != 'q':
if option == 'o':
print('OUTPUT SHOPPING CART')
Cart.print_total()
break
elif option == 'i':
print("OUTPUT ITEMS' DESCRIPTIONS")
Cart.print_descriptions()
break
elif option == 'a':
print('ADD ITEM TO CART')
print('Enter the item name:')
itemName = input()
print('Enter the item description:')
itemDescrip = input()
print('Enter the item price:')
itemPrice = int(input())
print('Enter the item quantity:')
itemQuan = int(input())
New_cart = ItemToPurchase()
New_cart.name = itemName
New_cart.quantity = itemQuan
New_cart.price = itemPrice
New_cart.description = itemDescrip
Cart.add_item(New_cart)
break
elif option == 'r':
print('REMOVE ITEM FROM CART')
print('Enter name of item to remove:')
ItemName = input()
Cart.remove_item(ItemName)
break
elif option == 'c':
print('CHANGE ITEM QUANTITY:')
print('Enter the item name:')
Item_Name = input()
print('Enter the new quantity:')
Item_Quantity = int(input())
item_s = ItemToPurchase()
item_s.item_quantity(Item_Quantity)
Cart.modify_item(item_s, Item_Name)
break**
if __name__ == "__main__":
print("Enter customer's name:")
customer = input()
print("Enter today's date:")
date = input()
print()
print('Customer name:', customer)
print("Today's date:", date)
Cart = ShoppingCart(customer, date)
option = ''
print()
print_menu(Cart)
print()
print('Choose an option:')
option = input().lower().strip()
execute_menu(option, Cart)
The reason why I am adding the break is cause the program keeps printing the end print item infinit amount of times if I do not add the break.
Any help is appreciated. thank you and have a great day ahead!
I am doing a schoolwork whereas I am doing a list where you add or remove cars and buyers. I have solved the car part, however I have trouble with adding the buyers part. I want the buyers to be added to the list, and removed at choice. I have partially solved the adding issue, however, whenever I try to remove a buyer it doesn't seem to work.
This is my code:
import json
import os.path
# Class
class Inventory:
cars = {}
buyers = {}
def __init__ (self):
self.load()
def add(self,key,qty):
q = 0
if key in self.cars:
v = self.cars[key]
q = v + qty
else:
q = qty
self.cars[key] = q
print(f'added {qty} {key}: total = {self.cars[key]}')
def add2(self,buy):
if buy in self.buyers:
b = self.buyers[buy]
else:
b = buy
self.buyers[buy] = b
print(f'added {buy}')
def remove2(self,buy):
if buy in self.buyers:
b = str(self.buyers[buy])
else:
b = buy
self.buyers[buy] = b
print(f'removed {buy}')
def remove(self,key,qty):
q = 0
if key in self.cars:
v = self.cars[key]
q = v - qty
if q < 0:
q = 0
self.cars[key] = q
print(f'removed {qty} {key}: total = {self.cars[key]}')
def display(self):
for key, value in self.cars.items():
print(f'{key} = {value}')
for buy in self.buyers.items():
print(f'{buy}')
def save(self):
print('saving information...')
with open('inventory4.txt', 'w') as f:
json.dump(self.cars,f)
json.dump(self.buyers,f)
print('information saved!')
def load(self):
print('loading information...')
if not os.path.exists('inventory4.txt'):
print('nothing to load!')
return
with open('inventory4.txt', 'r') as f:
self.cars = json.load(f)
self.buyers = json.load(f)
print('Information Loaded!')
def main():
inv = Inventory()
while True:
print('Write your choice...\n')
action = input('Choice:\nadd car, remove car, add buyer, remove buyer, list, save, exit: ')
if action == 'avsluta':
break
if action == 'add car' or action == 'remove car':
key = input('Add/remove specific car: ')
qty = int(input('Quantity: '))
if action == 'add car':
inv.add(key,qty)
if action == 'remove car':
inv.remove(key,qty)
if action == 'add buyer' or action == 'remove buyer':
buyers = input('Add/remove buyer: ')
if action == 'add buyer':
inv.add2(buyers)
if action == 'remove buyer':
inv.remove2(buyers)
if action == 'list':
print('____________________________________\n')
inv.display()
print('____________________________________\n')
if action == 'save':
inv.save
inv.save()
if __name__ == "__main__":
main()
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
I'm creating an invoice program that allows the user to select an item from a menu of products to either purchase or return. Once the user inputs the item ID and quantity desired, the program will read the inventory.txt file and write an UpdatedInventory.txt file, which will replace the inventory.txt file.
The inventory.txt file is formatted like this:
ID
item
stock
price
When my program runs, it does not print correctly on the UpdatedInventory.txt file. There's a lot of code here so bear with me.
As an aside, I feel like it would simplify the code if every purchase the user made was added into a list rather than hard coded. Thanks for the help!
Here's my main code:
import InventoryFile
import os
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])
#create inventory object
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 modify ():
found = False
search = -1
while search == -1:
search = input ('Enter the ID of the product you would like to purchase: ')
try:
if search == '0':
print ('The inventory has been updated...')
break
except Exception:
search = -1
print ('ERROR: Please enter a valid number.')
else:
inventoryFile = open ('inventory.txt', 'r')
temp_file = open ('UpdatedInventory.txt', 'w')
ID = str (inventoryFile.readline ())
while ID != '':
item = str (inventoryFile.readline ())
qty = float (inventoryFile.readline ())
price = float (inventoryFile.readline())
inventory_object = InventoryFile.Inventory (ID, item, qty, price)
ID = ID.rstrip ('\n')
if ID == search:
purchase = -1
while purchase == -1:
purchaseEntry = float (input ('How many would you like to purchase? Negative numbers are returns'))
purchase = inventory_object.purchase (purchaseEntry)
if purchase is False:
purchase = -1
print ('ERROR: Insufficient stock!')
new_qty = inventory_object.restock (purchase)
transaction_object = InventoryFile.TransactionItem (ID, item, new_qty, price)
transaction_object.set_id (ID)
transaction_object.set_name (item)
transaction_object.set_qty (new_qty)
transaction_object.set_price (price)
ID = transaction_object.get_id ()
item = transaction_object.get_name ()
qty = transaction_object.get_qty ()
price = transaction_object.get_price ()
temp_file.write (ID + '\n')
temp_file.write (item + '\n')
temp_file.write (str (qty) + '\n')
temp_file.write (str (price) + '\n')
found = True
else:
temp_file.write (ID + '\n' )
temp_file.write (item + '\n')
temp_file.write (str (new_qty) + '\n')
temp_file.write (str (price) + '\n')
ID = inventoryFile.readline ()
if found:
print ('The file has been updated.')
else:
print ('That item was not found in the file.')
inventoryFile.close ()
temp_file.close ()
os.remove ('inventory.txt')
os.rename ('UpdatedInventory.txt', 'inventory.txt')
print ('Inventory has been updated.')
break
return search
def main ():
all_items = readFile ()
printMenu (all_items)
modify ()
main ()
Here's my Inventory Class file:
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 += new_stock
return True
def purchase (self, purch_qty):
if self.__stock >= purch_qty:
self.__stock -= purch_qty
return self.__stock
else:
print ('ERROR: Insufficient stock')
return False
def __str__ (self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__stock, '7.2f') + format (self.__price, '7.2f')
class TransactionItem (Inventory):
def __init__ (self, new_id, new_name, new_qty, new_price):
self.__qty = new_qty
Inventory.__init__(self, new_id, new_name, new_qty, new_price)
def get_id (self):
return self.__id
def set_id (self, new_id):
self.__id = new_id
def get_name (self):
return self.__name
def set_name (self, new_name):
self.__name = new_name
def get_qty (self):
return self.__qty
def set_qty (self, new_qty):
self.__qty = new_qty
def get_price (self):
return self.__price
def set_price (self, new_price):
self.__price = new_price
def calc_cost (self):
total = purch_qty * self.__price
def __str__ (self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__qty, '7.2f') + format (self.__price, '7.2f') + \
format (total, '7.2f')
Here is my inventory.txt file:
244
Large Cake Pan
7
19.99
576
Assorted Sprinkles
3
12.89
212
Deluxe Icing Set
6
37.97
827
Yellow Cake Mix
3
1.99
194
Cupcake Display Board
2
27.99
285
Bakery Boxes
7
8.59
736
Mixer
5
136.94
And here is what the updated inventory txt looks like after I input product ID 244, and purchase quantity of 5.
244
Large Cake Pan
4.0
19.99
576
Assorted Sprinkles
4.0
12.89
212
Deluxe Icing Set
4.0
37.97
827
Yellow Cake Mix
4.0
1.99
194
Cupcake Display Board
4.0
27.99
285
Bakery Boxes
4.0
8.59
736
Mixer
4.0
136.94
I've disabled TransactionItem. This seems to be working (I've combined the script files):
import os
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 += new_stock
return True
def purchase(self, purch_qty):
if self.__stock >= purch_qty:
self.__stock -= purch_qty
return self.__stock
else:
print('ERROR: Insufficient stock')
return False
def __str__(self):
return self.__id + '\t' + self.__name + '\t' + \
format(self.__stock, '7.2f') + format(self.__price, '7.2f')
class TransactionItem (Inventory):
def __init__(self, new_id, new_name, new_qty, new_price):
self.__qty = new_qty
Inventory.__init__(self, new_id, new_name, new_qty, new_price)
def get_id(self):
return self.__id
def set_id(self, new_id):
self.__id = new_id
def get_name(self):
return self.__name
def set_name(self, new_name):
self.__name = new_name
def get_qty(self):
return self.__qty
def set_qty(self, new_qty):
self.__qty = new_qty
def get_price(self):
return self.__price
def set_price(self, new_price):
self.__price = new_price
def calc_cost(self):
self.total = purch_qty * self.__price
def __str__(self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__qty, '7.2f') + format (self.__price, '7.2f') + \
format(self.total, '7.2f')
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])
# create inventory object
inventory_object = 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 modify():
found = False
search = -1
while search == -1:
search = input(
'Enter the ID of the product you would like to purchase: ')
try:
if search == '0':
print('The inventory has been updated...')
break
except Exception:
search = -1
print('ERROR: Please enter a valid number.')
else:
inventoryFile = open('inventory.txt', 'r')
temp_file = open('UpdatedInventory.txt', 'w')
ID = str(inventoryFile.readline())
while ID != '':
item = str(inventoryFile.readline())
qty = float(inventoryFile.readline())
price = float(inventoryFile.readline())
inventory_object = Inventory(ID, item, qty, price)
ID = ID.rstrip('\n')
item = item.rstrip('\n')
if ID == search:
purchase = -1
while purchase == -1:
purchaseEntry = float(
input('How many would you like to purchase? Negative numbers are returns'))
purchase = inventory_object.purchase(purchaseEntry)
if purchase is False:
purchase = -1
print('ERROR: Insufficient stock!')
#new_qty = inventory_object.restock(purchase)
#transaction_object = TransactionItem(
# ID, item, new_qty, price)
#transaction_object.set_id(ID)
#transaction_object.set_name(item)
#transaction_object.set_qty(new_qty)
#transaction_object.set_price(price)
#ID = transaction_object.get_id()
#item = transaction_object.get_name()
#qty = transaction_object.get_qty()
#price = transaction_object.get_price()
qty = inventory_object.get_stock()
price = inventory_object.get_price()
temp_file.write(ID + '\n')
temp_file.write(item + '\n')
temp_file.write(str(int(qty)) + '\n')
temp_file.write(str(price) + '\n')
found = True
else:
temp_file.write(ID + '\n')
temp_file.write(item + '\n')
temp_file.write(str(int(qty)) + '\n')
temp_file.write(str(price) + '\n')
ID = inventoryFile.readline()
if found:
print('The file has been updated.')
else:
print('That item was not found in the file.')
inventoryFile.close()
temp_file.close()
os.remove('inventory.txt')
os.rename('UpdatedInventory.txt', 'inventory.txt')
print('Inventory has been updated.')
break
return search
def main():
all_items = readFile()
printMenu(all_items)
modify()
main()
I hope it helps!
Have you tried stepping thru the program?
https://docs.python.org/2/library/pdb.html or https://docs.python.org/3/library/pdb.html
at some point you're losing information
(its hard to troubleshoot that big block of code sadly)
I have an employee class which has an init method that reads an employees record in from a file. I also have an employees class which has an init_ method that attempts to read in all of the employee records.
I am having trouble with init for the employees class. Here is my code:
class EmployeeList():
records=[]
def __init__(self):
with open(database) as fp:
emp=employee(fp)
while (emp.id > 0):
print(emp)
self.records.append(emp)
emp=employee(fp)
The print(emp) is there for error checking, it shows that the records are being read in properly. When the EOF is reached, the init method for the employee sets the id to 0 and the name of the employee to "". I have two problems:
After the loop, all of the employees in employees.records are the same - id 0 and blanks for names. I am assuming that that emp is not creating a new instance each time it is called, and so all of the employees are being set to that one instance of emp, the very last one from when EOF is reached.
I doubt my code is "Pythonesque"; suggestions for improvement are welcome.
P.S. database is globally defined to the file name.
The entire code is here, sorry about the length:
class employee:
count = 0
def __init__(self,f=None):
if (f==None): # a user is inputting the employee
self.lastname = input("Employees last name:")
while type(self.lastname)!=type("1"):
print("Your input needs to be a name\n")
self.lastname = input("Employees last name:")
self.firstname = input("Employees first name:")
while type(self.firstname)!=type("1"):
print("Your input needs to be a name\n")
self.firstname = input("Employees first name:")
self.payrate = float(input("Employees pay rate:"))
while type(self.payrate)!=type(0.0):
print("Your input needs to be a pay rate\n")
self.payrate = float(input("Employees pay rate:"))
employee.count = employee.count + 1
self.id = employee.count
else: # the employee is being read in from the database and f is a file pointer
# read in an employee record and return false for end of file.
checkEOF = f.readline().rstrip('\r\n') #check for end of file
if (checkEOF != ""):
employee.id = int(checkEOF)
employee.firstname = f.readline().rstrip('\r\n')
employee.lastname = f.readline().rstrip('\r\n')
employee.payrate = float(f.readline().rstrip('\r\n'))
else:
employee.id = 0
employee.firstname = " "
employee.lastname = " "
employee.payrate = 0.0
def __hash__(self):
return hash(self.id)
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.id == other.id
return NotImplemented
def __str__(self):
return "Employee " + str(self.id) + " is "+self.firstname + " "+self.lastname+" and their pay rate is "+str(self.payrate)+"\n"
def __lt__(self, other):
if (self.lastname < other.lastname):
return True
elif (self.lastname > other.lastname):
return False
else: #same last names
if (self.firstname < other.firstname):
return True
elif (self.firstname > other.firstname):
return False
else: #same names
if (self.id < other.id):
return True
else: # note that ids cannot be the same
return False
def __gt__(self, other):
if (self.lastname > other.lastname):
return True
elif (self.lastname < other.lastname):
return False
else: # Same last names
if (self.firstname > other.firstname):
return True
elif (self.firstname > other.firstname):
return False
else: # Same names
if (self.id > other.id):
return True
else: # note that ids cannot be the same
return False
def payraise(self,payraise):
self.payrate = self.payrate+payraise
def saveemployee(self,fp):
fp.write(str(self.id)+"\n")
fp.write(self.firstname+"\n")
fp.write(self.lastname+"\n")
fp.write(str(self.payrate)+"\n")
class EmployeeList():
records=[]
def __init__(self):
with open(database) as fp:
emp=employee(fp)
while (emp.id > 0):
print(emp)
self.records.append(emp)
emp=employee(fp)
def __str__(self):
employeesprint = ""
for emp in self.records:
employeesprint = employeesprint + str(emp)
return employeesprint
def save(self):
self.records.sort()
with open(database,"w+") as fp:
fp.seek(0)
for emp in self.records:
emp.saveemployee(fp)
def menu():
print("\n")
print(choices[0]+". Add another employee")
print(choices[1]+". Print employees")
print(choices[len(choices)-1]+". Quit")
print("\n")
employees = EmployeeList()
choices = ["A","B","C"]
ch = "N"
while (ch != choices[len(choices)-1]):
menu()
ch=input("Make your choice ")
while not (ch in choices):
menu()
ch=input("Make your choice ")
if (ch == choices[0]):
employees.records.append(employee())
employees.save()
if (ch == choices[1]):
print(employees)
Sample output: You can see the two employees correctly being printed as they are read in:
Employee 1 is jane bob and their pay rate is 1.0
Employee 2 is jim bob and their pay rate is 3.4
A. Add another employee
B. Print employees
C. Quit
Make your choice B
Employee 0 is and their pay rate is 0.0
Employee 0 is and their pay rate is 0.0
your code:
if (checkEOF != ""):
employee.id = int(checkEOF)
employee.firstname = f.readline().rstrip('\r\n')
employee.lastname = f.readline().rstrip('\r\n')
employee.payrate = float(f.readline().rstrip('\r\n'))
else:
employee.id = 0
employee.firstname = " "
employee.lastname = " "
employee.payrate = 0.0
change 'employee' to 'self', 'employee' is the name of the class.