grocery list in python 3 - python-3.x

I'm confused about how to compare user input and a set list on python. For this problem, I have to create a program that asks the user for a list of ingredients. As the user enters the ingredients, I then need to store them in a list. Once the user is done entering their list, I need to pass this list to a function that will compare the ingredients to an already existing list of pantry items. If all items are available in the pantry, it should print out "you don’t need to go shopping". If any item is missing, it should print out "you need to go shopping" and list the missing ingredients. I've tried several ways of doing it but I can't figure it out.
So basically my function has to have:
1: A pre-created list for pantry items
2: User input into an ingredient list
3: Pass the ingredient list to a method
4: Use a conditional and loop in the method
5: Print out the results of whether the user needs to go shopping based on the items in the ingredient list that are not in the pantry.
This is what I have right now. Whenever I run it, it allows me to type in an item but then says <function end at 0x7fec87bf58b0> :
shopping_list = []
set_list = ['bread', 'jelly', 'peanut butter', 'chips']
#prints out what I need or if I have everything on my list
def end():
for item in shopping_list:
if shopping_list == set_list:
print("you have everything")
else:
print("You have to go grocery shopping! You need:" + str(new_list))
while True:
#asks for new items and removes them from the set list to return a new list
try:
new_item = input("Item? : ")
except ValueError:
print("Oops! That was no valid item. Try again...")
new_list = set_list.remove(new_item)
print(new_list)
if new_item == 'done':
print(end)

end is a function. When you write print(end) you ask python to print info about function. So it prints <function end at 0x7fec87bf58b0>. To print a result of a function you should call it first
So the end of your script will look like
if new_item == 'done':
result = end() # calling a function
print(result)

There you go:
pantry_items = ["apple", "banana", "eggs"]
ingridient_list = []
shopping_list = []
def compare_lists():
for item in pantry_items:
if item not in ingridient_list:
shopping_list.append(item)
userinput = ""
while (len(ingridient_list) < len(pantry_items)):
userinput = input("Enter smth.: ")
if (userinput == "done"):
compare_lists()
if len(shopping_list) > 0:
print("You need:")
print(shopping_list)
else:
print("You dont need to go shopping")
break
ingridient_list.append(userinput)
My python is a bit rusty, but this will do the job

Related

How do I calculate the total sum of my cart to my dictionary list based on user input menu?

I have created a simple menu to add things based on user input.
dictionary = {"Service A": 100, "Service B": 200}
cart = []
def main():
while(True):
print("1. List of Services")
print("2. Payment")
print("3. Exit")
print("\nServices you have added:", cart)
a = input("Please enter a choice: ")
if a=="1":
Q1()
elif a=="2":
Q2()
elif a=="3":
break
def Q1():
print('1. Service A : $100/year')
print('2. Service B : $200/year\n')
service = input("Enter the service 1-2 that you would like to add: ")
if not service.isnumeric():
print('Please enter valid choice number!')
elif service.isnumeric():
print(f'\nYou have selected choice number {service} which is: ')
if service == '1':
print ('\n''1. Service A: $100/year.''\n')
cart.append ("Service A")
if service == '2':
print ('\n''2. Service B: $200/year.''\n')
print('You will be return to main menu.')
cart.append ("Service B")
def Q2():
print("\nServices you have added:", cart)
#total = sum(cart)
#print('\nYour subscription will be a total of :',total)
main()
del(cart)
print("Goodbye and have a nice day!")
I need help in def Q2():
I want the services that I have added to my cart referencing to the dictionary list to get the total sum.
I'm not sure what is the exact codes. Please go easy on me, I'm a beginner.
def Q2():
print("\nServices you have added:", cart)
#total = sum(cart)
#print('\nYour subscription will be a total of :',total)
def Q2():
print("\nServices you have added:", cart)
total = 0
for i in cart:
total = total + dictionary[i]
#total = sum(cart) #This line of code will only merge the selected strings, not the sum of the numbers we need. Because the user added to the list named cart is a string instead of a number
print('\nYour subscription will be a total of :',total)
Hello, thank you for your question.
I added my note after the line of total = sum(cart) code: Because the user added to the list named cart is a string instead of a number. So we can use the for loop to use each string element in the cart as the key value of the dictionary to correspond to its value, and sum all the corresponding values, and finally declare a regional variable named total and store the sum.

Why will the variable 'basket' not be recognised when the choices 3 or 4 are chosen?

import time
shop = {'Processor': {'p3':100, 'p5':120, 'p7':200},
'RAM': {'16gb':75, '32gb':150},
'Storage': {'1tb':50, '2tb':100},
'Screen': {'19"':65, '23"':120},
'Case': {'Mini Tower':40, 'Midi Tower':70},
'USB Ports': {'2':10, '4':20}}
basket = []
def main():
print('''
Welcome to the PC Component Store!
Here, we sell you everything you will need.
(Keep in mind that display prices do NOT include VAT; this is added in checkout)
''')
options()
def productchoice():
a = 0
ptype = ''
pspec = ''
print('''
We assume you have taken a look at our catalog. To add an item to your basket here, you must:
> INPUT the type of product you are looking for, e.g: "RAM"
> Then, INPUT the specification of that type of item you desire, e.g: "16gb"
> We will process your request, and OUTPUT whether it has been accepted.
> If this does not work, we will allow you to try again. If you wish to return to menu, enter "MENU"
at each input prompt.
''')
while a == 0:
ptype = input('Product: ')
pspec = input ('Specification: ')
if ptype.lower() == 'menu' and pspec.lower() == 'menu':
print('''Returning to menu...
''')
options()
elif a == 0:
totalcost = 0
try:
totalcost += shop[ptype][pspec]
except:
print('''Your request was invalid. Please try again, and if you are unsure, return to
menu and revisit our catalog.
''')
continue
else:
addtocart(ptype,pspec)
print(totalcost)
print(basket)
else:
print('''Your request was invalid. Please try again, and if you are unsure, return to
menu and revisit our catalog.
''')
continue
def addtocart(ptype,pspec):
itemstr = ptype + ' ' + pspec
basket.append(itemstr)
return basket
def options():
a = 0
while a == 0:
choice = input('''Do you want to:
"SEE CATALOG"
"CHOOSE PRODUCT TO ADD TO BASKET"
"VIEW BASKET"
"CLEAR BASKET"
"CHECKOUT"
Enter a valid option using a number from (1-5): ''')
if choice == '1':
a = 1
print('WORK IN PROGRESS')
elif choice == '2':
a = 1
productchoice()
elif choice == '3':
a = 1
print('Your basket contains: ')
print(basket)
elif choice == '4':
a = 1
basket = []
print('''Basket cleared.'''
)
options()
elif choice == '5':
a = 1
checkout()
else:
print('''You must select a valid option from (1-5), taking you back to the menu...
''')
continue
main()
It comes up with an error saying 'UnboundLocalError: local variable 'basket' referenced before assignment' when 'basket' is used in options 3 or 4. What does this mean? Why when 'basket' is used in option 2, it works perfectly? I'm a GCSE student going into A-level who isn't that great at coding, so I thought stackoverflow could help.. this is really frustrating and I need to do it for homework..
You are facing a very common issue for most of new python developers and it is variable-scope problem. So, every variable has a its own scope, which means it can be referenced at some point in code in a very specific way. You can read here more about it.
As far as your problem holds, you can use a global key word at the start of function. Add this line:
global basket
at line # 91 and your program will run perfectly. This lines tells python to use the global basket list that you have created on line # 10.
Remember:
It should be noted that, use of global all around the code is not so much appreciated in python community, as it can lead to very complex code, if your code is very large and your modifying the global variable all across the code. If this is the case then its time to re-structure your code.

Why While Loop does not work in my program?

The assignment is to create a program that allows user to enter friend's name and phone number then print out contact list sorted by last name. Also to use function.
My problem is it only asks the user to make one action and then it just ask for details right away. It should ask the user to choose another action. Either to exit, add contact, show contacts or sort contacts.
def menu():
'''Display Menu'''
print(
"""
Contact Lists
0 - Exit
1 - Show Contacts
2 - Add Contacts
3 - Sort Contacts
"""
)
def ask():
user = None
user = input("Action: ")
print()
return user
def main():
menu()
action = ask()
names = []
while action != 0:
if action == "0":
print("Closing Contact Lists.")
elif action == "1":
print("Contact Lists: ")
for name in names:
print(name)
#setting a condition if user enter "2" it will let user add name, last name and phone number
elif action == "2":
name = input("Add contact's first name: ") #input 1
last_name = input("Add contact's last name: ") #input 2
contact_number = input("Add phone number for the contact name: ") #input 3
entry = (last_name, name, contact_number)
names.append(entry)
#setting a condition if user enter "3" it will sort contact list according to last names
elif action == "3":
entry.sort(reverse=True) #use of sort() to sort lists of by last names
print(names)
else:
print("Invalid Action!")
main()
Two errors in your code:
You should read user's input at the end of every loop.
Try to add action = ask() below your last else condition.
edit
code pieces:
#setting a condition if user enter "3" it will sort contact list according to last names
elif action == "3":
entry.sort(reverse=True) #use of sort() to sort lists of by last names
print(names)
else:
print("Invalid Action!")
action = ask()
sort() should be performed on names(a list), not entry(a tuple)

Python - shopping cart - problem with while loop

I am aiming to amend the quantity of an item from my shopping cart by removing the quantity of a particular item. I am using a while loop to do this, however my while loop does not seem to be ending.
I want it to end so that code goes back to choosing the option (1. add an item 2. amend 3. delete item 4. view basket)
Any ideas on how to achieve this efficiently?
Would greatly appreciate your help.
Thanks.
elif option == 2:
item2 = input("Select the item you would like to amend: Parcel or Letter: ")
item2_updated = item2.capitalize()
while item2_updated != None:
if item2_updated in shopping_basket:
print ("Current item quantity: ")
print(item2_updated,":",shopping_basket[item2_updated])
quantity = int(input("Enter the quantity to remove: "))
shopping_basket[item2_updated] = shopping_basket[item2_updated] - quantity
print(item2_updated,":",shopping_basket[item2_updated])
elif item2_updated != None:
print("Item not in the cart")
else:
print("Item not in the cart")
elif option == 3:
item = input("Enter an item: ")
del(shopping_basket[updated_item])
Firstly, you don't need
elif item2_updated != None:
print("Item not in the cart")
and avoid using while... else it's confusing.
Secondly, in your while loop you are not changing the value of item2_updated so item2_updated will never be None. It will always be the value the user initially sent in to input().
What you want to do is put the while loop at the very top and use if...elif...else to update and change. Something like this:
while True:
if option == 1:
# do something
elif option == 2:
if item2_updated in shopping_basket:
# do something (No while loop here)
else:
# do something else
You can also have a special option to "quit" which will break out of the while loop

Dictionary in Python not printing correctly

I want to print the contacts map but it doesn't work.
I removed all the if statements and it worked, but once I put the if statements in, it fails.
while True:
contacts = {}
print('''Type
1 to Add/Update contact
2 to Display all contacts
3 to Search
4 to Delete contact
5 to Quit.''')
choice = input("Which option?")
if int(choice) == 1:
contacts = {}
name = input("Enter the name of the contact.")
contact = input("Enter the phone number/email address.")
contacts[name] = contact
if int(choice) == 2:
print("Done!")
print(contacts)
if int(choice) == 3:
for key, value in contacts.items():
print(key)
The output is simply {}.
In each iteration of the while loop, you are clearing the contacts dictionary.
while True:
contacts = {}
...
should be
contacts = {}
while True:
...
it looks correct to me.
Maybe try
mycontact=contacts.keys()
phone=contacts.values()
print(mycontact)
print(phone)
If neighter of the solutions work (mine nor yours) try to doublecheck your if statement
choice = input("Which option?")
if int(choice) == 3:
print(this works)
else
print(this does not work)

Resources