pythonlistfunctionreturnshopping-cart

How to return into def menu in Shopping Cart List on Python


I'm practicing on a Shopping Cart including a list of items inputted by the user. This is how is going:

cart_items = []
price_items = []

print("Welcome to the Shopping Cart Program!")
print()

def menu():
        print("1. Add a new item")
        print("2. Display the content of the shopping cart")
        print("3. Remove an item of the shopping cart")
        print("4. Compute total of the items in the shopping cart")
        print("5. Quit")

def display_content():
    for i in range(0, len(cart_items)):
        print(f"{cart_items[i]} - {price_items[i]}")

menu()
option = int(input("Please, enter an action: "))

while option != 5:
    if option == 1:
        new_item = input("What item would you like to add? ")
        price_item = float(input(f"What is the price of the {new_item}? "))
        cart_items.append(new_item)
        price_items.append(price_item)
        print(f"{new_item} has been added to the cart.")
    if option == 2:
        print("The content of the shopping cart are:")
        display_content()
    if option == 3:
        new_item = input("Which item would you like to remove? ")
        temp = []
        for item in cart_items:
            if item[new_item] != new_item:
                temp.append(item)
    if option == 4:
        print('\n\n')
        summation = 0
        for item in cart_items:
            for product in cart_items:
                if product['id'] == item['id']:
                    summation = summation + \
                    (product['price'] * item['quantity'])
                    break
                print(f'The total price of the items in the shopping cart is ${0}'.format(summation))
    elif option >= 5:
        print("Invalid option, please, try again.")
print("Thank you for using the shopping cart program. Good bye!")

So, for the first option "1", the loop continues asking to add a new item.

I also made one first code that returns normally to the def menu that looks similar but simpler and is currently working as expected:

cart_items = []
price_items = []

print("Welcome to the Shopping Cart Program!")
print()

def menu():

        print("1. Add a new item")
        print("2. Display the content of the shopping cart")
        print("3. Quit")

def display_content():
    print(cart_items[0], price_items[0])
for i in range(0, len(cart_items)):
        print(f"{cart_items[i]} - {price_items[i]}")

menu()
option = int(input("Please, enter an action: "))

while option != 3:
    if option == 1:
        new_item = input("What item would you like to add? ")
        price_item = float(input(f"What is the price of the {new_item}? "))
        print(f"{new_item} has been added to the cart.")
        cart_items.append(new_item)
        price_items.append(price_item)
    elif option == 2:
        for i in range(len(cart_items)):
            items = cart_items
            print("The content of the shopping cart are:")
            display_content()
    else:
        print("Invalid option, please, try again.")

    print()
    menu()
    option = int(input("Please, enter an action: "))

print("Thank you for using the shopping cart program. Good bye!")

Not sure if I will be able to complete this program without help. I don't know, at the beginning, it looks good but in the end, taking some examples on YT is not helping me to get to the end of the program. Total disaster :(


Solution

  • You have to run menu() and input() inside while-loop.

    In first version you don't have it inside while-loop and it makes problem.

    But in second version you have it inside while-loop and it works.


    Simpler version

    while True:
    
         menu()
         option = int(input("Please, enter an action: "))
    
         if option == 5:
             break   # exit loop
    
         # ... check other options ...
    

    EDIT:

    Not tested

    # --- functions ---
    
    def menu():
            print("1. Add a new item")
            print("2. Display the content of the shopping cart")
            print("3. Remove an item of the shopping cart")
            print("4. Compute total of the items in the shopping cart")
            print("5. Quit")
    
    def add_item():
        name = input("What item would you like to add? ")
        price = float(input(f"What is the price of the {name}? "))
        cart.append( [name, price] )
        print(f"{name} has been added to the cart.")
    
    def display_content():
        print("The content of the shopping cart are:")
    
        for name, price in cart:
            print(f"{name} - {price}")
    
    def remove_item():
        selected_name = input("Which item would you like to remove? ")
        temp = []
        for name, price in cart:
            if name != selected_name:
                temp.append( [name, price] )
        cart = temp
        
    def total_sum():
        summation = 0
    
        for name, price in cart:
            summation += price
            
        print(f'The total price of the items in the shopping cart is ${summation}')
        
    # --- main ---
    
    cart = []  # keep pairs [name, price]
    
    print("Welcome to the Shopping Cart Program!")
    print()
    
    while True:
    
        menu()
        option = int(input("Please, enter an action: "))
    
        if option == 5:
            break
        
        elif option == 1:
            add_item()
            
        elif option == 2:
            display_content()
            
        elif option == 3:
            remove_item()
            
        elif option == 4:
            total_sum()
            
        else:
            print("Invalid option, please, try again.")
            
    print("Thank you for using the shopping cart program. Good bye!")