Problems reading and calculating items in list - python

I'm trying to use menus to accepts menu options that append an empty list that acts as a cart. When the list is done with i have the option to add more lists if necessary. In the end im supposed to calculate the total number of carts, total number of items, and the total price. The first issue is the calcuation of carts is wrong as it treats every new entry as list rather than na item, which elads to the item count being wrong as well for each cart. Along with this, i get "TypeError: unsupported operand type(s) for +: 'int' and 'str'" when trying calculating the final price and im just not sure what to do
def main():
#Flag for full checking out or not
checkout = False
#Flag to start a new cart or not
new_cart = True
#Placeholder list
cart = []
#List of items
book_list = [['My Own Words', 18.00], ['Grant', 24.50], ['The Overstory', 18.95], ['Becoming', 18.99]]
elec_list = [['HP Laptop', 429.50], ['Eyephone', 790.00], ['Bose Speakers', 220.00]]
cloth_list = [['T-shirt', 9.50], ['Shoes', 45.00], ['Pants', 24.00], ['Nationals Hat', 32.00]]
groc_list = [['Coho Salmon', 12.50], ['Spaghetti', 2.75], ['Milk', 3.99], ['Eggs', 1.99], ['Flat Tire Ale', 9.95]]
while checkout == False or new_cart == True:
#Main Menu
if checkout == False:
#Main Item menu
print("""
1 - Books
2 - Electronics
3 - Clothes
4 - Groceries
c - Continue to checkout
""")
choice = input("Select one of the categories or checkout(1-4 or 'c'): ")
#Variable to return user to past menu
Return = False
if choice == '1':
while Return == False:
#Sub item menu
print("""
1 - "My Own Words", $18.00
2 - "Grant", $24.50
3 - "The Overstory", $18.95
4 - "Becoming", $18.99
x - return to menu
""")
item = input("Please select from the menu or go back to the categories: ")
if item == '1' or item == '2' or item =='3' or item == '4':
#Adds item onto the the cart
cart.append(book_list[int(item)-1])
elif item == 'x':
#Returns user to main menu
Return = True
else: print("Invalid input try again")
elif choice == '2':
while Return == False:
#Sub item menu
print("""
1 - HP Laptop, $429.50
2 - EyePhone 10, $790.00
3 - Bose 20 Speakers, $220.00
x - return to menu
""")
item = input("Please select from the menu or go back to the categories: ")
if item == '1' or item == '2' or item == '3':
#Adds item onto the the cart
cart.append(elec_list[int(item)-1])
elif item == 'x':
Return = True
else:
print("Invalid input try again")
elif choice == '3':
while Return == False:
#Sub item menu
print("""
1 - T-shirt, $9.50
2 - Shoes, $45.00
3 - Pants, $24.00
4 - Nationals Hat, $32.00
x - return to menu
""")
item = input("Please select from the menu or go back to the categories: ")
if item == '1' or item == '2' or item == '3':
#Adds item onto the the cart
cart.append(cloth_list[int(item)-1])
elif item == 'x':
Return = True
else:
print("Invalid input try again")
elif choice == '4':
while Return == False:
#Sub item menu
print("""
1 – Coho Salmon, $12.50
2 − Spaghetti, $2.75
3 – Milk, $3.99
4 – Eggs, $1.99
5 – Flat Tire Ale, $9.95
x - return to menu
""")
item = input("Please select from the menu or go back to the categories: ")
if item == '1' or item == '2' or item == '3' or item == '4' or item == '5':
#Adds item onto the the cart
cart.append(groc_list[int(item)-1])
elif item == 'x':
Return = True
else:
print("Invalid input try again")
elif choice == 'c':
checkout = True
print(cart)
else: print("Invalid input, please try again!")
else:
print("Do you want a new cart y/n")
choice = input()
if choice == 'y':
checkout = False
#Create new cart
cart.append([])
elif choice == 'n':
#Proceed to item summary
new_cart = False
else:
print("Invalid Option, Choose again")
#Print total number of carts
print("Total number of carts :",len(cart))
for v in range(len(cart)):
#Increment for each existing cart
print("Cart",v+1)
#Add total number of items within every cart
print("Total Number of items:",len(cart[v]))
#Add total price of items within every cart
print("Total cost of the items: $",sum(cart[v]))
main()

Your cart contains a list of items which themselves are array:
example, i ran your code and your cart looks like this:
[['My Own Words', 18.0], ['My Own Words', 18.0], ['My Own Words', 18.0], ['My Own Words', 18.0]]
you're trying to apply a sum on a position of an array, so for example when you do
sum(cart[0]) you call sum on ['My Own Words', 18.0] so your code tries to do:
'My Own Words'+18 which gives a type error.
if all you need is the just the total price you could just append the prices instead of the whole items, or you could simply append the prices to a seperate array and call sum on that

Related

Python class bug

My remove and new quantity methods dont work and I have no idea why. Here is my code:
# Type code for classes here
class ItemToPurchase():
def __init__(self):
self.item_description = 'none'
self.item_name = 'none'
self.item_price= 0
self.item_quantity = 0
def print_item_description(self):
print(f'{self.item_name}: {self.item_description}')
class ShoppingCart():
def __init__(self, customer_name='none', current_date='January 1, 2016'):
self.customer_name = customer_name
self.current_date = current_date
self.items = []
def add_item(self, item ):
''' Adds an item to cart_items list. Has parameter of type ItemToPurchase. Does not return anything. '''
self.items.append(item)
def remove_item(self, item ):
''' Removes item from cart_items list. Has a string (an item's name) parameter. Does not return anything.
If item name cannot be found, output this message: Item not found in cart. Nothing removed. '''
delete = False
for item in self.items:
if self.items == item:
to_be_deleted = self.items[item]
delete = True
else:
print("Item not found in cart. Nothing removed.")
if delete == True:
del self.items[to_be_deleted]
def modify_item(self, item, new_quantity):
'''Modifies an item's quantity. Has a parameter of type ItemToPurchase. Does not return anything.
If item can be found (by name) in cart, modify item in cart.'''
if item in self.items:
item.quantity = new_quantity
else:
print("Item not found in cart. Nothing modified.")
def get_num_items_in_cart(self):
'''Returns quantity of all items in cart. Has no parameters.'''
num_items = 0
for item in self.items:
num_items += item.item_quantity
#return the num_Items
return num_items
def get_cost_of_cart(self):
'''Determines and returns the total cost of items in cart. Has no parameters.'''
return sum(item.item_price * item.item_quantity for item in self.items)
def print_total(self):
'''Outputs total of objets in cart.
If cart is empty, outputs this message: CART IS EMPTY.'''
print(f"{self.customer_name}'s Shopping Cart - {self.current_date}")
number_items = self.get_num_items_in_cart()
print(f'Number of Items: {number_items}\n')
total_cost = self.get_cost_of_cart()
if total_cost == 0:
print("SHOPPING CART IS EMPTY\n")
print(f'Total: ${total_cost}')
return False
else:
for item in self.items:
item_cost = item.item_quantity * item.item_price
print(f'{item.item_name} {item.item_quantity} # ${item.item_price} = ${item_cost}')
print()
total_cost = self.get_cost_of_cart()
print(f'Total: ${total_cost}')
def print_descriptions(self):
''' Outputs each item's description'''
print(f"{self.customer_name}'s Shopping Cart - {self.current_date}\n")
for item in self.items:
print("Item Descriptions")
print(f'{item.item.name}: {item.item_description}')
def print_menu():
print("MENU\na - Add item to cart\nr - Remove item from cart\nc - Change item quantity\ni - Output items' descriptions\no - Output shopping cart\nq - Quit\n")
def execute_menu(choice , shopping_cart):
if choice == "o":
print("OUTPUT SHOPPING CART")
shopping_cart.print_total()
elif choice == "i":
print("OUTPUT ITEMS' CART")
shopping_cart.print_descriptions()
elif choice == "a":
print("ADD ITEM TO CART\nEnter the item name:")
item_name = input()
print("Enter the item description:")
item_description = input()
print("Enter the item price:")
item_price = int(input())
print("Enter the item quantity:")
item_quantity = int(input())
New_item = ItemToPurchase()
New_item.item_name = item_name
New_item.item_price = item_price
New_item.item_quantity = item_quantity
New_item.item_description = item_description
shopping_cart.add_item(New_item)
elif choice =="r":
print("REMOVE ITEM FROM CART\nEnter name of item to remove:")
removed_item = input()
shopping_cart.remove_item(removed_item)
elif choice == "i":
'''Implement Change item quantity menu option in execute_menu(). Hint: Make new ItemToPurchase object before using ModifyItem() method. '''
print("CHANGE ITEM QUANTITY\nEnter the item name:")
Item = ItemToPurchase()
Item.item_name = input()
print("Enter the new quantity:")
Item.item_quantity = input()
if __name__ == "__main__":
shopping_cart = ShoppingCart()
print("Enter customer's name:")
shopping_cart.customer_name = input()
print("Enter today's date:")
shopping_cart.current_date = input()
print()
print(f"Customer name: {shopping_cart.customer_name}\nToday's date: {shopping_cart.current_date}")
print()
print_menu()
print("Choose an option:")
while True:
choice = input()
if choice in "arcioq":
if choice == 'q':
break
else:
execute_menu(choice, shopping_cart)
print()
print_menu()
print("Choose an option:")
I think with remove I'm comparing wrong data types and i cant seem to make it work. By the way, the function names cannot change and i cannot add any new functions. I can only use doc strings of preexisting methods and classes and functions
You're not using del correctly. I think you've confused del with the .remove() method of a list.
del self.items[to_be_deleted] makes no sense. self.items is a list, and list indexes must be integers. But to_be_deleted is not an integer; it is an actual item in the list.
If you want to use del, you need the integer index of the list item to be removed.
But since you have the actual object itself, you can call self.items.remove() instead, which takes the actual object as an argument.

while loop exiting instead of looping when criteria not met

i'm writing a function as part of a larger overall class project, and i'm having multiple issues with this looping statement, could any of you tell me how it's not looping even though its not meeting the exit criteria? i get what i need up until the loop, i'm trying to get it to ask you to select an item to add, print out the print statement, then start over and if you select the same item twice, add it to the cart
print("**********ITEMS**********")
print("1................Shirts - $10")
print("2.................Pants - $20")
print("3.................Shoes - $40")
print("4.................Dress - $50")
print("Complete Purchase")
cart = []
items = 0
def addItems():
items = int(input("please add an item to your cart: "))
while items > 0:
if items == 1:
print("Shirts,{}x,${}".format(+1, +10))
cart.count("Shirt")
cart.append("Shirt")
print(cart)
return cart
elif items == 2:
print("Pants,{}x,${}".format(+1, +20))
#cart.count("Pants")
cart.append("Pants")
return cart
elif items == 3:
print("Shoes,{}x,${}".format(+1, +40))
#cart.append("Shoes")
cart.count("Shoes")
return cart
elif items == 4:
print("Dress,{}x,${}".format(+1, +50))
#cart.append("Dress")
cart.count("Dress")
return cart
elif items > 5:
break
#return cart
# print(cart.count("Shirt") * 10 + cart.count("Pants") * 20 + cart.count("Shoes") * 40 + cart.count("Dress") * 50)
addItems()
this is my output below
please add an item to your cart: 1
Shirts,1x,$10
['Shirt']
Process finished with exit code 0
You should remove 'return cart' from your if-elif ladder and add it to outside of the while loop. Also you could take input from the user in while loop in addition to the previous one, at the end of the while loop.
def addItems():
items = int(input("please add an item to your cart: "))
while items > 0:
if items == 1:
print("Shirts,{}x,${}".format(+1, +10))
cart.count("Shirt")
cart.append("Shirt")
print(cart)
elif items == 2:
print("Pants,{}x,${}".format(+1, +20))
#cart.count("Pants")
cart.append("Pants")
elif items == 3:
print("Shoes,{}x,${}".format(+1, +40))
#cart.append("Shoes")
cart.count("Shoes")
elif items == 4:
print("Dress,{}x,${}".format(+1, +50))
#cart.append("Dress")
cart.count("Dress")
elif items > 5:
break
items = int(input("please add an item to your cart: "))
return cart

Python elif statements are changing type from float to list

First time posting so apologizes if formatting is incorrect. My program has 2 lists for now. I I will be adding 4 more after solving this initial issue. One for and item the user selects, and a second with prices for the each item. I have written a code for user selection which runs.
My issue comes with the code for the program associating the item selected with the price list. My first if statement registers item_price as a float, which I gives me what I need. Item_price in the following elif statements are being seen as a list. How can I change them to a float so that the price prints instead of the list?
food=["burger", "pizza", "hotdogs", "tacos"]
food_price=[8.99, 22.50, 3.50, 6.00]
def get_menu_item(item,item_list,):
phrase = "Would you like" + item + "? [y/n] "
response = input(phrase)
if response == "y":
print("Here are your menu options:", item_list)
idx = input("please enter the item you would like from our menu[1,2,3,4]: ")
idx = int(idx) -1
return item_list[idx]
#if user selects [n]
else:
return (None)
#item price function
def get_item_price(item_price,item,item_list):
if item == item_list[0]:
item_price = item_price[0]
elif item == item_list[1]:
item_price == item_price[1]
elif item == item_list[2]:
item_price == item_price[2]
elif item == item_list[3]:
item_price == item_price[3]
return item_price
entree_choice = get_menu_item(" dinner",food)
print('You have selected: ' + entree_choice + ".")
entree_price = get_item_price(food_price,entree_choice,food)
print(entree_price)
I answered this for myself shortly after. I was using == instead of = for all of my elif statements. I feel dumb but writing this out helped me solve it.
You could simplify things further by using a dictionary to store your data :
food_price = {"burger":8.99, "pizza":22.50, "hotdogs":3.50, "tacos":6.00}
def get_menu_item(item,item_list,):
phrase = "Would you like" + item + "? [y/n] "
response = input(phrase)
if response == "y":
print("Here are your menu options:", item_list)
idx = input("please enter the item you would like from our menu[1,2,3,4]: ")
idx = int(idx) -1
return item_list[idx]
else:
return (None)
entree_choice = get_menu_item(" dinner",food)
print('You have selected: ' + entree_choice + ".")
# if entree_choice is not found in the food_price dictionary, the output becomes the string "Entree choice not available."
entree_price = food_price.get(entree_choice, "Entree choice not available.")
print(entree_price)

trouble adding product prices to a list for checkout in python shopping program

This is a shopping cart program where the user can specify which items to put in the cart and how many, they select items from a list. For example, they can add the movie Frozen to the cart for 3 units. Each item has a price associated with it which is specified in a dictionary called ItemPriceInv. I have to put all of these item prices in a list for the number of times the item appears in cart in order to calculate the sum. This is what i have so far, it will only add one occurence of price for each unique item in cart while i need it to list the prices of items for as many times as they appear in the cart:
class Cart():
#prints options to screen
print('''
1: Add an Item
2: Remove an Item
3: View Cart
4: View List
5: Checkout
6: Exit
''')
#dictionary of item prices and inventory
ItemPriceInv = {'The Bourne Identity': [9.99, 200], 'Harry Potter': [15.99,1000], 'The Holy Grail': [4.75, 800],
'Arrival': [24.99, 900], 'Hidden Figures': [29.98, 3], 'Fantastic Beastes': [11.99, 2000],
'Frozen': [19.99, 77], 'The Godfather':[10.99 ,55], 'Analyze This': [8.99 ,20],
'American Splendor':[3.99, 50], 'Lego Movie': [19.99, 233], 'Transformers': [24.99, 500],
'Limitless': [29.99, 2], 'The Matrix': [10.99, 278]}
cart= {}
cost = []
command = int(input("Enter the option you would like to execute: "))
while command != 6:
if command == 1: #code for 'add item' option
product = input("Enter the product you would like to add: ")
if product == 'cart':
print(cart)
if product in ItemPriceInv:
NumofProducts = int(input('Enter the number of this product you would like to add to cart: '))
if NumofProducts > ItemPriceInv[product][1]:
print("We do not carry that quantity of", product)
print(cart)
else:
cart[product] = NumofProducts
ItemPriceInv[product][1]= ItemPriceInv[product][1]- NumofProducts
if product not in ItemPriceInv:
print('We do not carry this product :( ')
elif command == 2: #code for option 2
product = input('Enter an item to remove: ')
NumofProducts = int(input('How many of this item do you want to remove? '))
cart[product]-= NumofProducts
print(cart)
elif command == 3:
print(cart)
elif command == 4:
print(ItemPriceInv)
elif command == 5:
ItemPriceList = []
for item in cart:
ItemPrice = ItemPriceInv[item][0]
ItemPriceList.append(ItemPrice)
print(ItemPriceList)
#ItemPriceList.append(ItemPrice) #prices of items in cart
#L = list(itertools.repeat([ItemPrice, NumofProducts]))
#for ItemPrice in ItemPriceList:
#ItemPriceList = [ItemPrice] * NumofProducts
elif command != 6:
print('please enter a valid option')
command = int(input('Enter the option you would like to execute: '))
else:
print('Cart closed')
···
elif command == 5:
ItemPriceList = []
for item in cart:
ItemPrice = ItemPriceInv[item][0]
ItemNum = cart[item]
ItemPriceList.extend([ItemPrice]*ItemNum)
print(ItemPriceList)
what I have to say is that follow a good code style please.
And the unused code that with # just do what you want.

Python Assistance Searching a List

"""read file and store into database"""
f = open('C:\\Users\\user.name\\Desktop\\tunes.txt','r')
artist=[""]
song=[""]
album=[""]
genre=[""]
index=0
for line in f:
if index==0:
artist.append(line)
index=index+1
elif index==1:
song.append(line)
index=index+1
elif index==2:
album.append(line)
index=index+1
elif index==3:
genre.append(line)
index=index+1
elif index==4:
index=0
while 1:
selection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Search\n2.Recommend\n3.Edit\n4.Save\n"))
if selection == 1:
print "You selected Search"
searchselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Display All Songs\n2.Display All Artists\n3.Search By Artist\n4.Display All Genres\n5.Search by Genre\n6.Display All Playlists\n7.Search By Playlist\n"))
if searchselection == 1:
print '[%s]' % ''.join(map(str, song))
elif searchselection == 2:
print '[%s]' % ''.join(map(str, artist))
elif searchselection == 3:
artistsearch = str(raw_input("\nWhat artist are you searching for?\n"))
artist.index(artistsearch)
print value
elif searchselection == 4:
print '[%s]' % ''.join(map(str, genre))
elif searchselection == 5:
print "display"
elif searchselection == 6:
print "display"
elif searchselection == 7:
print "display"
break
elif selection == 2:
print "You selected recommend."
recommendselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Recommend by Song Title\n2.Recommend by Artist Name\n"))
if recommendselection == 1:
songrec = str(raw_input("Please enter the song title\n"))
elif recommendselection == 2:
artistrec = str(raw_input("Please enter the Artist's name\n"))
break
elif selection == 3:
print "You selected edit."
editselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Add a New Song\n2.Create New Playlist\n3.Add a song to a current playlist"))
if editselection == 1:
songadd = str(raw_input("Please enter the EVERYTHING\n"))
elif editselection == 2:
playistcreate = str(raw_input("Please enter the name of the Playlist\n"))
elif editselection == 3:
playlistadd = str(raw_input("Please enter the name of the playlist\n"))
break
elif selection == 4:
print "You selected Save."
f.close()
break
So that is what I have thus far. This is an ongoing python project, and right now I am stumped; I am trying to search by artist like if Justin Timberlake is typed in by the user as "artistsearch" then I want the index to be pulled so that I can match the index in the song list and display that information to the user.
Any help determining why Justin Timberlake is not a value on the list even though the name shows up when I run the display all artists option would be greatly appreciated.
Also being pointed in the right direction for matching list indexes would be great as well. This is an example of the tunes.txt:
Alicia Keys
No One
As I Am
R&B/Soul;Syl tunes
Everything But the Girl
Missing
Amplified Heart
Alternative;Syl tunes
Gathering Field
Lost In America
Lost In America
Rock
Ellie Goulding
Burn
Halcyon
Pop;Road tunes
Justin Timberlake
Mirrors
Mirrors (Radio Edit) - Single
Pop;Syl tunes
I think you should create a specific class for the data you want to store, and then create a list of objects that instantiate such class:
class Song():
"""Class to store the attributes for each song"""
def __init__ (self):
self.artist = ""
self.song = ""
self.album = ""
self.genre = ""
# List to store all the Song objects
songs_list = []
f = open('C:\\Users\\user.name\\Desktop\\tunes.txt','r')
index=0
for line in f:
# Instantiate an empty Song object
s = Song()
if index == 0:
s.artist = line
index=index+1
elif index == 1:
s.song = line
index = index + 1
elif index == 2:
s.album = line
index = index + 1
elif index == 3:
s.genre = line
index = index+1
elif index == 4:
index = 0
songs_list.append(s)

Categories

Resources