Search code examples
pythonflasksession-cookies

Shopping cart, how can I caclulate the total price of all the items in my cart


I have successfully been able to add to the basket using flask Sessions but I am having trouble with calculating the total price of all the products. I have tried to set a variable which calculates the price using the value in the list but that doesn't work and returns the first item instead. Could someone point me in the right direction?

@app.route("/Menu")
def menu():
    MenuItems = Menu.query.all()
    return render_template("menu.html", MenuItems=MenuItems)

@app.route("/AddToCart", methods=["POST", "GET"])
def addToCart():
    itemId = int(request.form.get("productId"))
    MenuItem = Menu.query.get(itemId)

    if MenuItem is None:
        return render_template("error.html", errorMessage="There has been an issue adding this item to your basket")

    sVars = session['cart']

    sVars.append([str(MenuItem.ItemName), float(MenuItem.ItemPrice)])
    session['cart'] = sVars

    allPrices = sum(sVars[1])

    return render_template("cart.html", cartSession=session['cart'], allPrices=allPrices)

Solution

  • So, you've got a list that looks like:

    sVars = [
        ['apple', 2.12],
        ['orange', 3.13],
    ]
    

    We just need a list of the second element of each list, that way we can do sum([2.12, 3.13]) and get our result. A neat way to do that is with a list comprehension:

    total_price = sum([x[1] for x in sVars])
    print(total_price)
    

    Which is a (in my humble opinion) neater way of doing:

    total_price = 0
    for entry in sVars:
        total_price += entry[1]
    print(total_price)
    

    As a secondary note-- generally Python recommends your variables are all lowercase svars compared to sVars using _ for spacing like total_price rather then totalPrice and leave the CamelCasing for class names, like you've got with MenuItem. It'll make your code a little easier for other people to look at and work with.