Python - shopping cart - problem with while loop - python-3.x

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

Related

grocery list in python 3

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

Unreachable code in if statement inside a while loop

I was trying to make a menu with a while loop to keep repeating until a valid input was entered. This is the code that I have:
print("1) Play game")
print("")
print("2) Instructions")
print("")
print("3) Quit")
print("")
while True:
try:
menu = int(input("Make a selection: "))
except ValueError:
print("Sorry, your input was not valid")
continue
if menu > 3 or menu < 1:
print("Please use a number in the range 1-3")
continue
else:
break
if menu == 1:
print("Lets go!")
elif menu == 2:
print("Lets go!")
else:
print("Quitting...")
The "if" where it says "if menu > 3 or menu < 1:" gives an error saying that:
"Unreachable codepylint(unreachable)"
Please help, it would be much appreciated.
Problem 1: continue statement
To help you understand your code, i used a flowchart to draw the lines for you.
However, if you move the continue inside the except statement, then the code will pass onto the if statement on a successful try statement.
The challenge is, that the code is never going into the if menu > 3.... statement, it always goes to try or except and then does the continue. So its looping itself skipping the if menu > 3 .... statement. That means, you never get out of the loop as it never gets to execute break.
Problem 2: You said you removed the continue statement.
When you remove continue from the statement, you create a new problem. If the code goes into except clause, variable menu did not get created properly. So when it goes to if menu > 3 ..., the variable has not been defined (due to except clause), and that gives you a new error.
Solution:
I would recommend to move the continue statement inside the except clause. That will take care of the problem. It will go back to while statement if there is an error with the input for menu. If it is successful, then your if menu > 3 ... will execute properly.
The modified correct code will be:
while True:
try:
menu = int(input("Make a selection: "))
except ValueError:
print("Sorry, your input was not valid")
continue #move this inside except
if menu > 3 or menu < 1:
print("Please use a number in the range 1-3")
continue
else:
break
if menu == 1:
print("Lets go!")
elif menu == 2:
print("Lets go!")
else:
print("Quitting...")

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.

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)

Unable to get out of loops

I'm trying to write a MasterMind game using classes and objects and I'm currently stuck around some of my loops.
while True:
# create a combination
# test the combination
while game_won == False:
print(scoreboard)
# player input combination
# combination is tested then added to scoreboard
tries_left = tries_left+1
if game_won == True:
print(You Won!)
input = Play Again? Y/N
if tries_left == 10:
print(You Lost!)
input = Play Again? Y/N
How do I do to go back to my while True -> create combination from my last if statement? (if tries_left == 10:)
What's wrong
Your first while True doesn't have anything in it, You need to indent code under it if you want it to be inside the loop.
There is a few typos, missing comment characters, and quotation marks.
What needs to happen
When the nested while loop while game_won == True exits, the code will return looping the parent loop while True, which will replay the game, if the user wishes.
Your code fixed (with a few improvements)
Following is how you can loop the game forever (given the user wishes it).
# Assume user wants to play when the program runs
user_wants_to_play = True
ans = ""
# loop the entire game while the user wishes to play
while user_wants_to_play:
# Create the combination
# Test the combination
# Game isn't done when started
game_done = False
tries_left = 10 # Arbitrary number I chose
while not game_done:
# Play the game
print("Scoreboard")
# Subtract one to tries left
tries_left -= 1
if game_done:
print("You won!")
elif tries_left == 0:
print("You lost!")
game_done = True
# if users answer was 'n'
ans = input("Play again? Y/N \n")
if ans.strip().upper() == 'N':
user_wants_to_play = False
Improvements
Boolean logic is more pythonic using not instead of myBool == False
while True: changed to while user_wants_to_play:
User input is scrubbed to ignore white-space and lower case
Changed game_won to game_done
Made tries_left count down instead

Resources