I'm new to python and programming in general.
I'm starting with my first mini project, a shopping cart.
I have everything working but I have been told I could get the whole loop going with just the outer one and that I do not require the second one. I've been wracking my brain all day trying to see how to get it to work, to no avail. Some pointers of how it can be achieved would be very much appreciated. Thank you.
shopping_list = []
print("Hi, Welcome to Jolly's Market.")
while True:
customer = input("To add to the shopping cart, press 1. To checkout and leave press 2.\n")
if customer == "1":
print("To return to the menu, type exit . To remove items, type r")
while customer != "exit" or customer != "r":
shopping_list.append(input("Add to cart: "))
print(shopping_list)
customer = input("").lower()
if customer == "exit":
print("Sending you back to the menu")
break
if customer == "r":
shopping_list.pop(int(input("Remove item ")))
print(shopping_list)
shopping_list.append(input("Add to cart: "))
print(shopping_list)
customer = input("").lower()
if len(shopping_list) == 10:
print("You have ten items, do you wish to add more? (y, n)")
customer = input(" ").lower()
if customer == "y":
shopping_list.append(input("Add to cart: "))
elif customer == "n":
print("Sending you back to the main menu")
break
The inner while loop is not required because it can be done with only the outer while loop.
Here's how you can modify the code:
shopping_list = []
print("Hi, Welcome to Jolly's Market.")
while True:
customer = input("To add to the shopping cart, press 1. To checkout and leave press 2.\n")
if customer == "1":
print("To return to the menu, type exit . To remove items, type r")
item = input("Add to cart: ")
shopping_list.append(item)
print(shopping_list)
customer = input("").lower()
if customer == "exit":
print("Sending you back to the menu")
continue
if customer == "r":
shopping_list.pop(int(input("Remove item ")))
print(shopping_list)
item = input("Add to cart: ")
shopping_list.append(item)
print(shopping_list)
customer = input("").lower()
if len(shopping_list) == 10:
print("You have ten items, do you wish to add more? (y, n)")
customer = input(" ").lower()
if customer == "y":
item = input("Add to cart: ")
shopping_list.append(item)
elif customer == "n":
print("Sending you back to the main menu")
continue
elif customer == "2":
break
Here, the inner while loop is not required because the menu options are already in the outer loop. When the user types 1, the shopping list is updated, and then the user is asked to either add or remove items. If the length of the shopping list reaches 10, the user is asked if they want to add more. If the user types exit or n, they are sent back to the main menu. If the user types 2, the while loop breaks and the program ends.
Here's a revised version of the code that will let you continuously add items to the shopping list without being taken back to the main menu after each item, until you reach 10 items or decide to exit:
shopping_list = []
print("Hi, Welcome to Jolly's Market.")
while True:
customer = input("To add to the shopping cart, press 1. To checkout and leave press 2.\n")
if customer == "1":
print("To return to the menu, type exit . To remove items, type r")
while True:
item = input("Add to cart: ")
shopping_list.append(item)
print(shopping_list)
if len(shopping_list) == 10:
print("You have ten items, do you wish to add more? (y, n)")
customer = input(" ").lower()
if customer == "n":
break
else:
continue
customer = input("").lower()
if customer == "exit":
print("Sending you back to the menu")
break
if customer == "r":
shopping_list.pop(int(input("Remove item ")))
print(shopping_list)
continue
elif customer == "2":
break
Related
I am a complete beginner in learning Python. Currently working on an assignment and having issues in creating menu with submenus.I am trying to connect functions properly and make my program work.
How can I make my submenu work? Output doesnt show the submenu options.
type def display_header():
main = "Main Menu"
txt = main.center(90, ' ')
print('{:s}'.format('\u0332'.join(txt)))
print("Please choose an option from the following menu:")
print("I. Invitee's Information")
print("F. Food Menu")
print("D. Drinks Menu")
print("P. Party Items Menu")
print("Q. Exit")
def get_user_choice():
choice = input("Enter your choice: ")
return choice
def invitees_menu():
invitees_menu()
while True:
choice = invitees_menu()
if choice == "a":
enter_invitee()
if choice == "e":
edit_invitee()
if choice == "v":
drinks_menu()
if choice == "b":
display_header()
print("Invitees' Information Menu")
print("Please choose an option from the following menu:")
print("A. Add new invitee information")
print("E. Edit existing invitee information")
print("V. View all invitees")
print("B. Go back to main menu")
choice = input("Enter your sub-menu choice: ")[0].lower
return choice
if __name__ == "__main__":
display_header()
while True:
choice = get_user_choice()
if choice == "i":
invitees_menu()
if choice == "f":
food_menu()
if choice == "d":
drinks_menu()
if choice == "p":
party_menu()
if choice == "q":
print ("Thank you for using the program!")
break
I might be wrong in understanding the code, but here's what I think's happened.
when you call your invitees_menu function it immediately calls itself. This breaks a rule of recursion (a function calling itself) and causes an infinite loop of just calling the start of the function over and over again. Which gives us this error:
RecursionError: maximum recursion depth exceeded
So first i'd remove the first invitees_menu line completely. Then in the while loop you're calling the invitees_menu again. This is again the same problem because each time you call the function, it will call itself again and never get to returning any item. Here i've replaced it with:
print("Invitees' Information Menu")
print("Please choose an option from the following menu:")
print("A. Add new invitee information")
print("E. Edit existing invitee information")
print("V. View all invitees")
print("B. Go back to main menu")
choice = input("Enter your sub-menu choice: ")[0].lower
You then have the problem of never actually leaving the while True loop. Since entering B should break out and then go back to the main loop in the __main__ call, so i replaced the display_header with break.
Finally, the last few smaller things are:
removing the "type" at line 1
moving the display header in main inside the while loop
fixing up the irregular tab structure in invitees_menu
And here it is
def display_header():
main = "Main Menu"
txt = main.center(90, ' ')
print('{:s}'.format('\u0332'.join(txt)))
print("Please choose an option from the following menu:")
print("I. Invitee's Information")
print("F. Food Menu")
print("D. Drinks Menu")
print("P. Party Items Menu")
print("Q. Exit")
def get_user_choice():
choice = input("Enter your choice: ")
return choice
def invitees_menu():
while True:
print("Invitees' Information Menu")
print("Please choose an option from the following menu:")
print("A. Add new invitee information")
print("E. Edit existing invitee information")
print("V. View all invitees")
print("B. Go back to main menu")
choice = input("Enter your sub-menu choice: ")[0].lower()
if choice == "a":
enter_invitee()
if choice == "e":
edit_invitee()
if choice == "v":
drinks_menu()
if choice == "b":
break
return choice
if __name__ == "__main__":
display_header()
while True:
choice = get_user_choice()
if choice == "i":
invitees_menu()
if choice == "f":
food_menu()
if choice == "d":
drinks_menu()
if choice == "p":
party_menu()
if choice == "q":
print ("Thank you for using the program!")
break
I suggest as first step to clean up the mess with recursive function calls in following section:
def invitees_menu():
invitees_menu()
while True:
choice = invitees_menu()
Next step in cleaning up the mess would be to remove the entire unnecessary parts of the code preventing the sub-menu from showing up when calling invitees_menu().
I wanted a create a function in Python where the user inputs the name of the menu and then it returns it in their order. After they are finished with ordering, the function would then calculate the price. My problem is I typed "Apple", but it came back empty. Is there anyway I could get around this? Any assistance is appreciated.
Here is the function:
menu = [{"Menu":"Apple","Price":9.00},{"Menu":"Banana","Price":5.00}], my_order = [], userInput = 0
try:
userInput = input("Enter item menu name that you want to select >> ") except ValueError:
print("Item does not exist.") if userInput in menu:
print("The item is in the list") else:
print("The item is not in the list. Please choose a different item.") while userInput != "Stop" or userInput != "stop":
print(f"Available menu: {menu}")
userInput = input("Do you want to add the item from the menu? If so please type appropriate item menu name. If no please type Stop. >> ")
if userInput == "Stop" or userInput == "stop":
print("The program has ended no more items will be added.")
print(f"Your order: {my_order}")
break
elif userInput not in menu:
print("Item does not exist in the list, try another item.")
print(f"Your order: {my_order}")
continue
else:
menu["Menu"] = userInput
my_order.append(userInput)
print(f"Your order: {my_order}")
continue
The way you use a dictionary is to have a key and a value related to it, in this case your menu dictionary should be {"item":price}.
That way if you want to know the price of an Apple yo do
print(menu["Apple"])
Did not understand why the Try/except in this case.
menu = {"Apple" : 9.00, "Banana" : 5.00}
my_order = []
userInput = ""
while userInput != "Stop" or userInput != "stop":
print(f"Available menu: {menu}")
userInput = input("Do you want to add the item from the menu? If so please type appropriate item menu name. If no please type Stop. >> ")
if userInput == "Stop" or userInput == "stop":
print("The program has ended no more items will be added.")
print(f"Your order: {my_order}")
break
elif userInput not in menu:
print("Item does not exist in the list, try another item.")
print(f"Your order: {my_order}")
continue
else:
my_order.append(userInput)
print(f"Your order: {my_order}")
continue
I let you continue calculating the total for the bill.
Goal:
After the user inputs whether they want to add another new item or not I want the code to start over at the newItem input line so that I don't have to just keep the if-train going and end up adding a cap to it.
Listed below is the code I've written so far.
shopping_cart_menu = []
shopping_cart_prices = []
print("Welcome to the shopping cart program. Please select an option from the menu below.")
print("*******************")
print("01: Add a new Item")
print("02: Display Cart contents")
print("03: Remove Item")
print("04: Compute Total")
print("05: Quit")
print("*******************")
menuAnswer = input(" ")
if menuAnswer == "01":
newItem = input("What item would you like to add? ")
shopping_cart_menu.append({newItem})
followUp = input("Would you like to add another item? Y/N: ")
if answer = "Y"
Here is how you can use a while loop:
menuAnswer = input(" ")
if menuAnswer == "01":
while True:
newItem = input("What item would you like to add? ")
shopping_cart_menu.append({newItem})
followUp = input("Would you like to add another item? Y/N: ")
if answer != "Y":
break
Using a while loop will allow you to loop the if statements. The line "followup = followup.upper()" will capitalise the input too.
shopping_cart_menu = []
shopping_cart_prices = []
print("Welcome to the shopping cart program. Please select an option from the menu below.")
print("*******************")
print("01: Add a new Item")
print("02: Display Cart contents")
print("03: Remove Item")
print("04: Compute Total")
print("05: Quit")
print("*******************")
menuAnswer = input(" ")
if menuAnswer == "01":
followup = "Y"
while followup == "Y":
newItem = input("What item would you like to add? ")
shopping_cart_menu.append({newItem})
followup = input("Would you like to add another item? Y/N: ")
followup = followup.upper()
I am trying to create a reading list, using 2 functions - one to add books and another to display books. The add books function need to execute till such time user confirms that the update is completed. Following is the code :
book_list = []
def add_books(books):
book_record = {}
completed = "no"
while completed == "no":
title = input("Enter title : ")
author = input("Enter author : ")
year = input("Enter year of publication : ")
book_record.update({"title": title, "author": author, "year_publ": year})
books.append(book_record)
print(books)
completed = input("update completed ? yes/no")
return books
def display_books(books):
for book in books:
title = book["title"]
author = book["author"]
year = book["year_publ"]
print(f"{title}, {author}, {year}")
option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")
while option != "q" :
if option == "a":
book_list = add_books(book_list)
elif option == "d":
display_books(book_list)
else:
print("Invalid Option")
option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")
When I execute this code, the While loop ignores the completed condition and keeps asking for adding more books even though the user confirms updated completed.
What is wrong ? I understand that I am trying to update completed inside the loop, and that may be the reason. What are the options ?
Appreciate any help.
Thanks and Regards
Sachin
So the problem is with the option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :"). You are asking only one time for the option, what you need is an endless loop to continue asking for the new option. On your approach when the "user" chooses the "a" option he/she never gets asked again so the options still remains on "a" thus the add_books() function running endless!
You should change the last part to:
while True:
option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")
if option == "a":
book_list = add_books(book_list)
elif option == "d":
display_books(book_list)
elif option == "q":
quit()
else:
print("Invalid Option")
Did you tried this?:
def add_books(books):
book_record = {}
completed = "no"
while True:
title = input("Enter title : ")
author = input("Enter author : ")
year = input("Enter year of publication : ")
book_record.update({"title": title, "author": author, "year_publ": year})
books.append(book_record)
print(books)
completed = input("update completed ? yes/no")
if completed == 'yes':
break
return books
Your code keeps asking because option still is "a" after add_books has finished, and your "main" loop does not get a new value for option from the user.
Always make the "Do you want to continue?" question part of the loop.
I would recommend to use endless loops (while True:) with a conditional break for these kinds of tasks. It's easier to follow (in my opinion):
Like this - I've added a helper function input_letter that returns the trimmed, lower-case first letter of the user's response, for easier management later):
book_list = []
def input_letter(prompt):
return input(prompt).strip().lower()[0::1]
def add_books(books):
while True:
title = input("Enter title: ")
author = input("Enter author: ")
year = input("Enter year of publication: ")
books.append({"title": title, "author": author, "year_publ": year})
if input_letter("More? (y)es / (n)o ") == "y":
break
return books
def display_books(books):
for book in books:
title = book["title"]
author = book["author"]
year = book["year_publ"]
print(f"{title}, {author}, {year}")
while True:
option = input_letter("(a)dd book, (d)isplay books, (q)uit: ")
if option == "a":
add_books(book_list)
elif option == "d":
display_books(book_list)
elif option == "q":
break
if you whant to keep ypur code use:
another condintion to tell the loop that the completed have been updated and quit it!
book_list = []
def add_books(books):
book_record = {}
completed = "no"
while completed == "no":
title = input("Enter title : ")
author = input("Enter author : ")
year = input("Enter year of publication : ")
book_record.update({"title": title, "author": author, "year_publ": year})
books.append(book_record)
print(books)
completed = input("update completed ? yes/no")
if completed == "yes":
completed = completed
break
return books
def display_books(books):
for book in books:
title = book["title"]
author = book["author"]
year = book["year_publ"]
print(f"{title}, {author}, {year}")
option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")
while option != "q" :
if option == "a":
book_list = add_books(book_list)
elif option == "d":
display_books(book_list)
else:
print("Invalid Option")
option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")
I'm trying to create a code for my lists work and i have written this at the moment:
list = [ ]
def Menu(choice):
print("""Menu:
1. View entire list
2. View one item
3. Reset list
4. Edit list
5. Quit
""")
choice = int(input("Please choose an option: "))
while True:
if choice == "1":
print (list)
Menu()
elif choice == "2":
oneItem = int(input('Please enter an item to view (1-5): '))
oneItem = oneItem - 1
oneView = list[(oneView)]
print (oneView)
Menu()
elif choice == "3":
list = [None]*6
Menu()
elif choice == "4":
def carryon():
for i in range(6):
add = input("Please enter a new item for the list: ")
list.append(add)
carryOn = input("Would you like to carry on? (y/n): ")
if carryOn == "y":
carryon()
else:
break
break
Menu()
When I run the code in shell the menu appears fine:
Menu:
1. View entire list
2. View one item
3. Reset list
4. Edit list
5. Quit
Please choose an option: 3
But then it just comes up blank. I can type things in still but nothing happens. Even after i press enter it just carries on. I use python 3.4 (gui)