I am trying to build shopping cart using Python 3. I could remove item by item name but I tried to remove item by index while iterating through a cart with the below code.
def removeItem(index):
clear_output()
for index in range(len(cart)):
try:
cart.pop(index)
#del cart[index]
print('{} has been remove from cart.'.format(index))
except:
print('Sorry we could not remove that item.')
I add two items into the cart: bacon and egg. then I show the cart:
def showCart():
clear_output()
if cart:
print('Here is your cart:')
for item in cart:
#print('- {}'.format(item))
print(cart.index(item)+1, item) # show item with index
else:
print('Your cart is empty.')
Then, I tried to remove an item from cart with its index (which begin with 1 as in showCart() function), however, it always removes the first item and the output:
0 has been remove from cart.
Sorry we could not remove that item.
please let me know if my question is not clear enough.