Home > Blockchain >  Why am I getting this output? (Shopping Cart Program)
Why am I getting this output? (Shopping Cart Program)

Time:05-06

Current Code Snippet:

for x in range(len(cart) 1):
    if book[int(bookInput)- 1][1] in cart:
        cart[x][0] =1
    else:
        cart.append([1,book[int(bookInput)- 1][0],book[int(bookInput)- 1][1]])

Current Output:

[[1, 'The Lincoln Highway', 30.0], [1, 'The Lincoln Highway', 30.0], [1, 'The Lincoln Highway', 30.0]]
[[1, 'The Lincoln Highway', 30.0], [1, 'The Lincoln Highway', 30.0], [1, 'The Lincoln Highway', 30.0]]
[[1, 'The Lincoln Highway', 30.0], [1, 'The Lincoln Highway', 30.0], [1, 'The Lincoln Highway', 30.0]]

Output desired:

    [[2, 'The Lincoln Highway', 30.0]]

I'm creating a counter for each item to prevent duplicates from being added to the shopping cart list. Been banging my head against my keyboard for days and I can't figure this out! It doesn't recognize that the item is already in the cart.

CodePudding user response:

You're checking if string 'The Lincoln Highway' is the list of entries (lists) e.g. [1, 'The Lincoln Highway', 30.0] so that's why your check fails

added = False # so we know whether to add a new entry at the end
for i in cart:
    if book[int(bookInput)- 1][1] == i[1]: 
        i[0]  = 1
        added = True
        break
if not added:
    cart.append([1,book[int(bookInput)- 1][0],book[int(bookInput)- 1][1]])

Even better, would be to implement cart as set/dict since you will be checking membership quite often e.g.

cart = { "book" : (quantity, price)}
if book in cart: 
    q, p = cart[book]
    cart[book] = (q 1, p)

or similar.

CodePudding user response:

The else: shouldn't be on the if statement. That will cause you to add a new item to the cart for every existing item that doesn't match the current book.

Use the else: clause of the for loop. This executes if the loop runs to completion. Then inside the loop, use break to stop early if you find the matching book.

title = book[int(bookInput)-1][0]
for item in cart:
    if item[1] == title:
        item[0]  = 1
        break
else:
    cart.append([1, title, book[int(bookInput)-1][1]
  • Related