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 !')
``
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()
How can I input products with 'prod_id' and 'prod_name' as keys in respective category_id. When a user requests for category_id_2 he should be able to add 'prod_id' and 'prod_name' in that particular category.
{
{
'category_id_1':{'prod_id': 'f1a1', 'prod_name': 'apple'},
{'prod_id': 'f1a2', 'prod_name': 'banana'},
{'prod_id': 'f1a2', 'prod_name': 'banana'}
},
{
'category_id_2':{'prod_id': 'v1b1', 'prod_name': 'bottle gourd'},
{'prod_id': 'v1c1', 'prod_name': 'cauli flower'}
},
}
Below is the code of the following!
import sys
inventory = []
final_temp = {}
class Inventory:
def __init__(self):
self.temp_category_data = {}
def add_category(self,category_id):
self.temp_category_data = {category_id:{}}
print(self.temp_category_data)
def add_products(self,category_id,prod_id,prod_name):
self.temp_category_data = {category_id:{}}
self.temp_category_data[category_id]['prod_id'] = prod_id
self.temp_category_data[category_id]['prod_name'] = prod_name
# final_temp.add(self.temp_category_data)
inventory.append(self.temp_category_data)
x = input("Enter [0] to exit and [1] to continue:\n")
while x != '0':
if x=='0':
print("Bye!")
sys.exit()
if x=='1':
y = input("\nEnter \n[1] Add Categories \n\t[1a] Add to existing category \n[2] Add Products\n[3] Search Categories \n[4] Search Products and \n[5] Delete Product\n")
if y == '1':
categoryId = input("\nEnter The Category ID: ")
# categoryName = input("\nEnter The Category Name: ")
inv = Inventory()
inv.add_category(categoryId)
print(inventory)
continue
if y == '2':
categoryId = input("\nEnter The Category ID: ")
prodId = input("\nEnter The Product ID: ")
prodName = input("\nEnter The Product Name: ")
inv = Inventory()
inv.add_products(categoryId,prodId,prodName)
print(inventory)
else:
print("Wrong input Details!!")
sys.exit()
x = input("Enter [1] to continue and [0] to exit:\n")
Basically i want to implement a inventory management system!
I think you can optimize your dictionary to look like this:
{'category A':
{'Product Id A1' : 'Product Name A1',
'Product Id A2' : 'Product Name A2'},
'category B':
{'Product Id B1' : 'Product Name B1',
'Product Id B2' : 'Product Name B2',
'Product Id B3' : 'Product Name B3'}
}
This will allow for you to search for the category and product id quickly.
Example of this would be:
{'Fruits':
{'Fruit_Id_1': 'Apple',
'Fruit_Id_2': 'Banana',
'Fruit_Id_3': 'Grapes'},
'Animals':
{'Animal_Id_1': 'Bear',
'Animal_Id_2': 'Goose'}
}
To create , search, and delete the contents in a nested dictionary, you can use the below code:
cat_dict = {}
def category(opt):
while True:
cname = input ('Enter Category Name : ')
if cname == '': continue
if opt == '1' and cname in cat_dict:
print ('Category already exist. Please re-enter')
elif opt != '1' and cname not in cat_dict:
print ('Category does not exist. Please re-enter')
else:
return cname
def product(cname,opt):
while True:
pid = input ('Enter Product Id : ')
if pid == '': continue
elif opt == '1': return pid
elif opt == '2' and pid in cat_dict[cname]:
print ('Product Id already exist. Please re-enter')
elif opt != '2' and pid not in cat_dict[cname]:
print ('Product Id does not exist. Please re-enter')
else:
return pid
while x:=input("Enter [0] to exit:\n") != '0':
while True:
options= input('''Enter
[1] Add Categories
[2] Add Products
[3] Search Categories
[4] Search Products
[5] Delete Category
[6] Delete Product
> ''')
if options not in ('1','2','3','4','5','6'):
print ('Incorrect Entry. Please re-enter\n')
else:
break
#Valid option has been selected
#Get Category Name
cat_name = category(options)
#Get Product Id
if options in ('1','2','4','6'):
prod_id = product(cat_name,options)
#Get Product Name
if options in ('1','2'):
while True:
prod_name = input ('Enter Product Name : ')
if prod_name != '': break
#Ready to process options 1 thru 6
#Option 1: Insert Category, Product Id, and Product Name
if options == '1':
cat_dict[cat_name] = {prod_id : prod_name}
#Option 2: Insert Product Id, and Product Name for given Cateogry
elif options == '2':
cat_dict[cat_name].update({prod_id : prod_name})
#Option 3: print out all Product Id and Product Name for requested Category
elif options == '3':
print ('All Products with',cat_name, 'are :', cat_dict[cat_name])
#Option 4: print out the Product Name for requested Category and Product Id
elif options == '4':
print ('Product Name for ',prod_id, 'is :', cat_dict[cat_name][prod_id])
#Option 5: Delete the requested Category and all Product Ids and Product Names
elif options == '5':
confirm_delete = cat_dict.pop(cat_name, None)
if confirm_delete is not None:
print ('Category :',cat_name,'successfully deleted')
#Option 6: Delete the Product Id and Product Name within the given Category
else:
confirm_delete = cat_dict[cat_name].pop(prod_id, None)
if confirm_delete is not None:
print ('Product Id :', prod_id, 'in category:', cat_name,'successfully deleted')
I have tested this and it works properly. Let me know if you find any bugs or areas of improvement.
Your code is a bit of a mess logically so I'm offering two approaches
in add_category change
self.temp_category_data = {category_id:{}}
to be a list:
self.temp_category_data = {category_id:[]}
and in add_products change the way you add stuff from to be append, because its a list
self.temp_category_data[category_id]['prod_id'] = prod_id
self.temp_category_data[category_id]['prod_name'] = prod_name
to
self.temp_category_data[category_id].append({'prod_id':prod_id, 'prod_name':prod_name})
this way you will have a list of dictionaries, but will have to look through it to find any specific one.
Another approach, which will work if "prod_id" are unique per category, is to only change add_products like this:
self.temp_category_data[category_id][prod_id] = prod_name
this will give you a single dictionary which doesnt require you to search through
Hope you find this helpful.
inventory = {}
class Inventory:
def add_category(self,category_id):
inventory[category_id] = {}
print(inventory)
def add_products(self,category_id,prod_id,prod_name):
inventory[category_id]['prod_id'] = prod_id
inventory[category_id]['prod_name'] = prod_name
x = input("Enter [0] to exit and [1] to continue:\n")
while x != '0':
if x=='0':
print("Bye!")
sys.exit()
if x=='1':
y = input("\nEnter \n[1] Add Categories \n\t[1a] Add to existing category \n[2] Add Products\n[3] Search Categories \n[4] Search Products and \n[5] Delete Product\n")
if y == '1':
categoryId = input("\nEnter The Category ID: ")
# categoryName = input("\nEnter The Category Name: ")
inv = Inventory()
inv.add_category(categoryId)
print(inventory)
continue
if y == '2':
categoryId = input("\nEnter The Category ID: ")
prodId = input("\nEnter The Product ID: ")
prodName = input("\nEnter The Product Name: ")
inv = Inventory()
inv.add_products(categoryId,prodId,prodName)
print(inventory)
else:
print("Wrong input Details!!")
sys.exit()
x = input("Enter [1] to continue and [0] to exit:\n")
Output:{'Food': {'prod_id': 'Meat', 'prod_name': 'Meat'}, 'Fruits': {'prod_id': 'Melon', 'prod_name': 'Melon'}}
I am doing a University project to create a plan ordering ticket program, so far these are what I have done:
First, this is the function finding the seat type:
def choosingFare():
print("Please choose the type of fare. Fees are displayed below and are in addtion to the basic fare.")
print("Please note choosing Frugal fare means you will not be offered a seat choice, it will be assigned to the ticketholder at travel time.")
listofType = [""] * (3)
listofType[0] = "Business: +$275"
listofType[1] = "Economy: +$25"
listofType[2] = "Frugal: $0"
print("(0)Business +$275")
print("(1)Economy +$25")
print("(2)Frugal: $0")
type = int(input())
while type > 2:
print("Invalid choice, please try again")
type = int(input())
print("Your choosing type of fare is: " + listofType[type])
if type == 0:
price1 = 275
else:
if type == 1:
price1 = 25
else:
price1 = 0
return price1, listofType[type]
And this is a function finding the destination:
def destination():
print("Please choose a destination and trip length")
print("(money currency is in: Australian Dollars: AUD)")
print("Is this a Return trip(R) or One Way trip(O)?")
direction = input()
while direction != "R" and direction != "O":
print("Invalid, please choose again!")
direction = input()
print("Is this a Return trip(R) or One Way trip(O)?")
if direction == "O":
print("(0)Cairns oneway: $250")
print("(2)Sydney One Way: $420")
print("(4)Perth One Way: $510")
else:
print("(1)Cairns Return: $400")
print("(3)Sydney Return: $575")
print("(5)Perth Return: $700")
typeofTrip = [""] * (6)
typeofTrip[0] = "Cairns One Way: $250"
typeofTrip[1] = "Cairns Return: $400"
typeofTrip[2] = "Sydney One Way: $420"
typeofTrip[3] = "Sydney Return: $575"
typeofTrip[4] = "Perth One Way: $510"
typeofTrip[5] = "Perth Return: $700"
trip = int(input())
while trip > 5:
print("Invalid, please choose again")
trip = int(input())
if trip == 0:
price = 250
else:
if trip == 1:
price = 400
else:
if trip == 2:
price = 420
else:
if trip == 3:
price = 574
else:
if trip == 4:
price = 510
else:
price = 700
print("Your choice of destination and trip length is: " + typeofTrip[trip])
return price, typeofTrip[trip]
And this is the function calculating the total price:
def sumprice():
price = destination()
price1 = choosingFare()
price2 = choosingseat()
sumprice = price1 + price2 + price
print("How old is the person travelling?(Travellers under 16 years old will receive a 50% discount for the child fare.)")
age = float(input())
if age < 16 and age > 0:
sumprice = sumprice / 2
else:
sumprice = sumprice
return sumprice
The error I have:
line 163, in <module> main()
line 145, in main sumprice = sumprice()
line 124, in sumprice
sumprice = price1 + price2 + price
TypeError: can only concatenate tuple (not "int") to tuple
Can someone help me? I am really stuck.
I can't return all the
These functions return 2 values each: destination(), choosingFare(), choosingseat().
Returning multiple values at once returns a tuple of those values:
For example:
return price, typeofTrip[trip] # returns (price, typeofTrip[trip])
So while calculating the sum of all prices, you need to access price, price1, price2 from the tuples:
sumprice = price1[0] + price2[0] + price3[0]
Alternatively: You can edit the code to return list/ dictionary or some other data structure as per your convenience.
First let me explain what happends when you write. return price, typeofTrip[trip].
The above line will return a tuple of two values.
Now for sumprice I think what you want is sum of all prices. So you just want to sum first element of returned values.
This should work for your case.
sumprice = price1[0] + price2[0] + price3[0]
I have written a program for a homework assignment, that should function as a mock grocery list that will calculate how much the items should cost as well.
grocery_item = {}
grocery_history=[{'name': 'milk', 'number': int(1), 'price': float(2.99)},
{'name': 'eggs', 'number': 2, 'price': 3.99},
{'name': 'onions', 'number': 4, 'price': 0.79}]
stop = 'go'
item_name = "Item name"
quantity = "Quantity purchased"
cost = "Price per item"
print ("Item name:")
print ("Quantity purchased:")
print ("Price per item:")
cont = 'c'
while cont != 'q':
item_name = "milk"
quantity = "Quantity purchased"
quantity = 2
cost = "Price per item"
cost = 2.99
grocery_history.append(item_name)
grocery_history.append(quantity)
grocery_history.append(cost)
grocery_item['name'] = item_name
grocery_item['number'] = quantity
grocery_item['price'] = cost
print("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")
cont = 'c'
item_name = "eggs"
quantity = "Quantity purchased"
quantity = 1
cost = "Price per item"
cost = 3.99
grocery_history.append(item_name)
grocery_history.append(quantity)
grocery_history.append(cost)
grocery_item['name'] = item_name
grocery_item['number'] = quantity
grocery_item['price'] = cost
"Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n"
cont = 'c'
item_name = "onions"
quantity = "Quantity purchased"
quantity = 4
cost = "Price per item"
cost = 0.79
"Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n"
cont = 'q'
grand_total = []
number = grocery_item['number']
price = grocery_item['price']
for grocery_history in grocery_item:
item_total = number*price
grand_total.append(item_total)
print (grocery_item['number'] + ['name'] + "#" + ['price'] + "ea" + ['item_total'])
item_total = 0
print (grand_total)
This is the error I get:
print (grocery_item['number'] + ['name'] + "#" + ['price'] + "ea" + ['item_total'])
TypeError: unsupported operand type(s) for +: 'int' and 'list'
There are multiple problems with this code.
I am supposed to use the %.2f to get the price in dollar form, but I have no idea how, and the things I've tried haven't worked.
There are syntax errors in my print(grocery_item) statement.
The code doesn't run through the list grocery_history, and just repeats with the same input over and over.
To get a formatted print with the fields from the dict you can use .format() like:
print('{number} {name} # {price:.2f} ea'.format(**grocery_item))
You have an error because you are adding string to floats. Python does not know how to do that.
As #Stephen Rauch showed, you can do it in one line with a very pythonic structure. If you want you can use the syntax
'%s\t%s\t...'%(my_variable1, my_variable2)
Which works great as well.
I assume you wanted to add items to already existing grocery_history and then calculate the grand total of all your groceries (using Stephen Rauch's printing answer).
grocery_history=[{'name': 'milk', 'number': int(1), 'price': float(2.99)},
{'name': 'eggs', 'number': 2, 'price': 3.99},
{'name': 'onions', 'number': 4, 'price': 0.79}]
cont = 'c'
grand_total = 0
while cont != 'q':
num = input("How many bottles of milk do you want to buy? ")
grocery_history[0]['number'] += num
num = input("How many eggs do you want to buy? ")
grocery_history[1]['number'] += num
num = input("How many onions do you want to buy? ")
grocery_history[2]['number'] += num
cont = raw_input("Enter c to continue or q to quit: ")
while cont not in ['c', 'q']:
cont = raw_input("Wrong choice, enter your choice again: ")
for grocery_item in grocery_history:
item_total = grocery_item['number'] * grocery_item['price']
grand_total += item_total
print('${:.2f} for {number} {name} # {price:.2f} ea'.format(item_total, **grocery_item))
print ("Grand total is ${:.2f}".format(grand_total))
Some of what went wrong:
You weren't actually asking the user to enter c or q, so you just went once over the list and exited in the end because of cont = 'q'.
You were constantly overwriting your variables, for example:
quantity = "Quantity purchased"
quantity = 2
First line assigns string and the second - integer. You can operate directly on dict values, provided you know how to access them.
This part:
number = grocery_item['number']
price = grocery_item['price']
assigned the last actually updated grocery_item (eggs) and you did all your calculations in for loop with these two values.
Here:
grocery_history.append(item_name)
grocery_history.append(quantity)
grocery_history.append(cost)
you were appending strings and numbers to a list of dictionaries.