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()
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!
#------------------------create------------------------------
def create(car_id, make, model, year, body_type):
row = [car_id, make, model, year, body_type]
data.append(row)
return f"created car with id {car_id}"
#------------------------delete-----------------------------------
def delete (car_id, id_to_delete):
global c_id
for row in data:
c_id = row[0]
if car_id == id_to_delete:
data.remove(row)
break
pass
#------------------------selecting-------------------------------
def select_by_id(c_id):
for row in data:
car_id = row[0]
if car_id == c_id:
selection.append(row)
return f"selected car with id {c_id}"
def select_all():
global selection
selection = data
#-----------------------input loop------------------------------------
def input_loop():
while(1):
line = input()
tokens = line.split()
cmd = tokens[0]
if cmd == "create":
print(tokens[1:])
'''
car_id = tokens[1]
make = tokens[2]
model = tokens[3]
year = tokens[4]
result = create(car_id, make, model, year)
'''
result = create(*tokens[1:5])
print(result)
elif cmd == "exit":
print("goodbye")
break
elif cmd == "update":
result = update(*tokens[1:4])
else:
print("invalid or not implemented command: {cmd}")
input_loop()
#--------------------------------updating----------------------
def update(car_id, attr, val):
row = get_row(car_id)
if row:
print(f"updating{attr}")
i = headers.index(attr)
print(f"index: {i}")
print(row[i])
row[i] = val
pass
#------------------------print selection------------------------------
def print_selection():
headers = ['id','make','model','year','body_type']
for row in selection:
print(headers)
print(row)
pass
#-------------------------main--------------------------------------
def main():
create("0", "Toyota", "Highlander", "2015")
create("1", "Toyota", "Highlander", "2016")
create("2", "Toyota", "Highlander", "2017")
delete("1")
result = select_by_id("1")
print(result)
result = select_by_id("2")
print(result)
print_selection()
main()
I keep on getting a list index out of range error, and I'm not sure why it's happening or where to fix it. Any help would be greatly appreciated.
[enter image description here]
error code
This is my code:
#cart is a list, easy to append
cart=['S/n'," "*10, 'Items', " " * 14, "Quantity", " " * 8, "Unit Price", " " * 8, "Price"]
total_pricee = 0
pricee = 0
count=1
from datetime import datetime
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print( "Date & Time:",dt_string)
print('Welcome to tis program.Please use the numbers to navigate!')
def invalid_input(Quantitiy):
while Quantitiy > '5' or Quantitiy < '1':
Quantitiy = input("Please key in a valid quantity(Between 1 to 5):")
if Quantitiy < '5' and Quantitiy > '1':
New_Quan=Quantitiy
#This part of function checks if item quantity is between 1 and 5
return Quantitiy
break
while not Quantitiy.isdigit():
Quantitiy = input('Invalid input.Please enter a valid input:')
while Quantitiy.isdecimal() == False:
break
#This part of function checks that item quantity is not a decimal
return Quantitiy
def add_to_cart(name, Quantity, price):
global total_pricee, pricee,count,cart
#This function adds items to cart
cart.append('\n')
cart.append('{:<10s}'.format(str(count) + '.'))
cart.append('{:^10s}'.format(name))
cart.append('{:^30s}'.format(str(Quantity)))
cart.append('$'+str(price)+'0')
pricee = '{:.2f}'.format(float(Quantity) * price)
pricee
cart.append('{:^34s}'.format('$' +str(pricee)))
total_pricee += float(pricee)
count = count +1
print(name,"has been added to cart!")
def remove_from_cart(Item_number):
global count
while True:
if Item_number>(count-1):
print('Please key in a valid S/n!')
(Item_number)=int(input('Please enter the S/n of the item you want to remove:'))
if Item_number==2:
cart.pop(9)
cart.pop(9)
cart.pop(9)
cart.pop(9)
cart.pop(9)
cart.pop(9)
if Item_number<=(count-1):
x=(6*(Item_number-2))+9
cart.pop(x)
cart.pop(x)
cart.pop(x)
cart.pop(x)
cart.pop(x)
cart.pop(x)
print('Item has been sucsussfully removed from cart!')
if count==1:
print('Please add an item to cart first!')
while True:
print('[1] Water')
print('[2] rice')
print('[3] ice')
print('[0] View Cart and Check-out')
print("[4] Remove object from cart")
opt = input("Select option:")
if opt > '4' or opt < '0':
print("Select valid option!")
if opt == '3':
qunt = input("Please key in a quanity for your item:")
qunt =invalid_input(qunt)
nam3 = "Ice"
add_to_cart(nam3, qunt, 2.00)
if opt == '1':
qunt2 = input("Please key in a quanity for your item:")
qunt2=invalid_input(qunt2)
nam2 = " Water"
add_to_cart(nam2, qunt2, 3.00)
if opt == '2':
qunt1 = input("Please key in a quanity for your item:")
qunt1=invalid_input(qunt1)
nam1 = "Rice"
add_to_cart(nam1, qunt1, 5.00)
if opt == "0":
print(*cart)
print("Total price until now:", "$" + '{:.2f}'.format(total_pricee))
print('Would you like to check out?')
print('[1] Yes')
print('[2] No')
checkout=input("Please select an option:")
if checkout=='1':
print('You have bought',count,'items')
print("Please pay""$" + '{:.2f}'.format(total_pricee))
print('Thank you for shopping with us!')
exit()
if opt=="4":
print(*cart)
remove=input("Please key in the S/n of the item you want to remove:")
remove_from_cart(int(remove))
print(*cart)
I do not know why this error is occurring .I am a bit new to python and have not encounter such error before.Please tell me how to improve my code such that this error does not occur again. Thanks to anyone who helps!
For eg:
S/n Items Quantity Unit Price Price
1. Rice 3 $5.00 $15.00
2. Rice 4 $5.00 $20.00
3. Water 4 $3.00 $12.00
and user wants to remove the second item, it the output after the function has been carried out should be
S/n Items Quantity Unit Price Price
1. Rice 3 $5.00 $15.00
2. Water 4 $3.00 $12.00
I can't paste the formatted code in the comment, I will write it in the answer, I hope to understand.
The list is very inconvenient to do this operation
In [1]: import pandas as pd
In [5]: d = pd.DataFrame([['Rice', 3, '$5.0', '$15.0'], ['Water', 4, '$3.0', '$12.0']], columns=['Items', 'Quantity', 'Unit Price', 'Price'])
In [6]: d
Out[6]:
Items Quantity Unit Price Price
0 Rice 3 $5.0 $15.0
1 Water 4 $3.0 $12.0
In [7]: d.drop(0)
Out[7]:
Items Quantity Unit Price Price
1 Water 4 $3.0 $12.0
In [16]: d.append([{"Items": "Rice", "Quantity": 3, "Unit Price": "$5.0", "Price": "$20.0"}], ignore_index=True)
Out[16]:
Items Quantity Unit Price Price
0 Rice 3 $5.0 $15.0
1 Water 4 $3.0 $12.0
2 Rice 3 $5.0 $20.0
Here's my code, maybe for your reference :)
from itertools import repeat
class Cart():
def __init__(self):
self.header = ['S/N', 'Items', 'Quantity', 'Unit Price', 'Price']
(self.SN_width, self.item_width, self.quantity_width,
self.unit_price_width, self.price_width
) = self.widths =[13, 19, 16, 18, 20]
self.item_list = {}
def get_serial_no(self):
i = 1
while i in self.item_list:
i += 1
return i
def add(self, item, quantity, unit_price):
serial_no = self.get_serial_no()
self.item_list[serial_no] = (item, quantity, unit_price)
def delete(self, serial_no):
del self.item_list[serial_no]
lst = sorted(self.item_list.keys())
new_list = {i+1:self.item_list[key] for i, key in enumerate(lst)}
self.item_list = new_list
def sum_all(self):
all_price = 0
for item, quantity, unit_price in self.item_list.values():
all_price += quantity*unit_price
return all_price
def adjust(self, items):
line = ['']*5
for i in range(5):
if i == 0:
line[0] = items[0].center(self.widths[0])
elif i == 1:
line[1] = items[1].ljust(self.widths[1])
else:
line[i] = items[i].rjust(self.widths[i])
return ' '.join(line)
def __repr__(self):
keys = sorted(self.item_list.keys())
title = self.adjust(self.header)
seperator = ' '.join(list(map(str.__mul__, repeat('-'), self.widths)))
result = [title, seperator]
for key in keys:
lst = self.item_list[key]
items = [str(key), lst[0], '%.3f'%lst[1], '$%.3f'%lst[2],
'$%.3f'%(lst[1]*lst[2])]
line = self.adjust(items)
result.append(line)
return '\n'.join((' ', '\n'.join(result), ' ',
'Total price: $%.3f'%self.sum_all(), ' '))
cart = Cart()
new_items = [
('apple', 10, 1), ('orange', 5, 0.5), ('banana', 20, 0.2),
('avocado', 5, 0.2), ('cherry', 1, 20), ('grape', 1, 15), ('lemon', 5, 1)]
for item in new_items:
cart.add(*item)
while True:
print(cart)
try:
action = input('Add(A), Delete(D), Exit(E) :').strip().lower()
except:
continue
if action == 'a':
try:
item = input('Name of item: ').strip()
quantity = float(input('Quantiy: ').strip())
unit_price = float(input('Unit Price: ').strip())
except:
print('Wrong data for item !')
continue
cart.add(item, quantity, unit_price)
elif action == 'd':
key = input('Serial No. to be deleted: ').strip()
try:
key = int(key)
if key in cart.item_list:
cart.delete(int(key))
continue
except:
pass
print('Wrong serial No. !')
elif action == 'e':
break
else:
print('Wrong action !')
print('Bye !')
``
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 this dict for example and i wish to return the nth value of it
d = {'Hello':4, 'World':17, 'Hi':2, 'Again':46}
Note: I know that dicts are unordered, and i don't care i just want to return all the keys one after the other.
In my program I just want to make calculations with the values, and the keys will be a user input so we don't know the keys.
How can i return the nth value in this dict like this?
Hereis the full code of y progam, error is located in 2nd def function, on line 23
#Subroutines
def dumptodaydate():
import pickle
with open('LastOpenDate.txt', 'wb') as DOT:
import time
ODate = time.strftime('%d')
OMonth = time.strftime('%m')
OYear = time.strftime('%Y')
List = {'Day':ODay, 'Month':OMonth, 'Year':OYear}
pickle.dump(List, DOT)
def caltimelefttask():
import pickle
with open('LastOpenDate.txt', 'rb') as LOD:
List = pickle.load(LOD)
from datetime import date
Today = date.today()
ODay = List['Day']
OMonth = List['Month']
OYear = List['Year']
DifDay = (Today(eval(OYear),eval(OMonth), eval(ODay)).days
for key in Lesson:
OTimetask = Lesson[key]['TimeLeftTask']
TimeLeft = OTimetask - DifDay
Rating = Rating + (TimeLeft * 2)
if Timeleft == 0 and OTimetask > 3:
Rating = Rating + 100
elif OTimetask > 0 and TimeLeft == 0:
Rating = Rating + 50
elif OTimetask > 4 and imeLeft == 0 and OTimetask != 0:
Rating = Rating + 50
Lesson[key]['Rating'] = Rating
for key in Exercises.keys():
OTimetask = Exercises[key]['TimeLeftTask']
TimeLeft = OTimetask - DifDay
Rating = Rating + (TimeLeft * 2)
if Timeleft == 0 and OTimetask > 3:
Rating = Rating + 100
elif OTimetask > 0 and TimeLeft == 0:
Rating = Rating + 50
elif OTimetask > 4 and imeLeft == 0 and OTimetask != 0:
Rating = Rating + 50
Exercises[key]['Rating'] = Rating
for key in Assignment.keys():
OTimetask = Assignment[key]['TimeLeftTask']
TimeLeft = OTimetask - DifDay
Rating = Rating + (TimeLeft * 2)
if Timeleft == 0 and OTimetask > 3:
Rating = Rating + 100
elif OTimetask > 0 and TimeLeft == 0:
Rating = Rating + 50
elif OTimetask > 4 and imeLeft == 0 and OTimetask != 0:
Rating = Rating + 50
Assignment[key]['Rating'] = Rating
def loadtxt():
import pickle
with open('LessonOut.txt', 'rb') as Li:
Lesson = pickle.load(Li)
with open('ExercisesOut.txt', 'rb') as Ei:
Exercises = pickle.load(Ei)
with open('AssignmentOut.txt', 'rb') as Ai:
Assignment = pickle.load(Ai)
def ADD():
print('Name of task? (Keep it short for convenience Example: Math1)\n(Must be diferent from any other non deleted tasks)')
Name = input('>>>')
print('Description of task? (this can be as long as you want)')
Desc = input('>>>')
print('Rate the time it takes you to do the task on a scale from 1 to 20')
Time = input('>>>')
print('Rate the importance of the task on a scale from 1 to 20')
Imp = input('>>>')
print('Rate how much you want to do it on a scale from 1 to 5 \n(1= want to do it, 5= don\'t want to')
Want = input('>>>')
print('enter deadline (day)')
TimeDay = input('>>>')
print('enter deadline (month)')
TimeMonth = input('>>>')
print('enter deadline(year)')
TimeYear = input('>>>')
print('what type of homework is it? (Lesson/Exercises/Assignment)')
TaskType = input('>>>')
from datetime import date
Today = date.today()
TaskForDate = date(eval(TimeYear), eval(TimeMonth), eval(TimeDay))
TimeLeftTemp = abs((TaskForDate - Today).days)
print ('You have', TimeLeftTemp, 'days to finish this task.')
Rating = eval(Time) + eval(Imp) + eval(Want) - (TimeLeftTemp * 2)
if TimeLeftTemp < 4:
Rating = Rating + 50
if TimeLeftTemp <= 0:
Rating = Rating + 50
if TaskType == 'Lesson':
Lesson[Name] = {'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':TimeLeftTemp}
if TaskType == 'Exercises':
Exercises[Name] = {'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':TimeLeftTemp}
if TaskType == 'Assignment':
Assignment[Name] = {'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':TimeLeftTemp}
def DEL():
print ('What type of task is it? \nLesson, Exercises or Assignment)')
WhatDict = input('>>>')
if WhatDict == Lesson:
print(Lesson.keys())
if WhatDict == Exercises:
print(Exercises.keys())
if WhatDict == Assignment:
print(Assignment.keys())
print ('What task do you want do delete?')
WhatDel = input('>>>')
if WhatDict == 'Lesson':
try:
del Lesson[WhatDel]
except:
pass
elif WhatDict == 'Exercises':
try:
del Exercises[WhatDel]
except:
pass
elif WhatDict == 'Assignment':
try:
del Assignment[WhatDel]
except:
pass
pass
else:
print('Sorry, the type of task is not recognised, please try again.')
def sort_by_subdict(dictionary, subdict_key):
return sorted(dictionary.items(), key=lambda k_v: k_v[1][subdict_key])
def SHOW():
ShowWhat = input('What type of task do you want to do?\nLesson/Exercises/Assignment)\n>>>')
if ShowWhat == 'Lesson' or 'lesson':
print (sort_by_subdict(Lesson, 'Rating'))
elif ShowWhat == 'Exercises' or 'exercises':
print (sort_by_subdict(Exercises, 'Rating'))
elif ShowWhat == 'Assignment' or 'assignment':
print (sort_by_subdict(Assignment, 'Rating'))
else:
print('Type of task not recognosed, please try again')
def dumptxt():
import pickle
with open('LessonOut.txt', 'wb') as Lo:
pickle.dump(Lesson, Lo)
with open('ExercisesOut.txt', 'wb') as Eo:
pickle.dump(Exercises, Eo)
with open('AssignmentOut.txt', 'wb') as Ao:
pickle.dump(Assignment, Ao)
loadtxt()
while True:
print ('WARNING NEVER EXIT PROGRAM WITHOUT USING THE quit COMMAND,\nOR ALL ACTIONS DONE WILL BE LOST')
print ('Commands:')
print ('add (to add a task)')
print ('del (to delete a task)')
print ('quit (to exit program)')
print ('show (to see your tasks)')
Input = input('>>>')
if Input == 'add':
ADD()
elif Input == 'del':
DEL()
elif Input == 'show':
SHOW()
elif Input == 'quit':
print ('are you sure you want to quit? y/n')
Input = input('>>>')
if Input == 'y':
dumptxt()
quit()
elif Input == 'n':
print ('Not exiting')
else:
print ('Error, command not recognised')
This gives me a syntax error:
for key in Lesson:
#syntax error ^
# here
You can just enumerate over all the keys in the dict directly by using for key in d:
for key in d:
if d[key] < 20:
d[key] -= 4
else:
d[key] += 4