0

So I'm implementing "buy" in pset7 CS50 Finance, and having trouble with it. When I type in my stock and shares, the error is: "TypeError: unorderable types: list() > float()". This seems to be referring to my line of code that says:

if cash > shares*price:

My full code is below, but it seems like when I select the cash value from my SQL table, it is producing a list as opposed to a float (which is what I want it to do). I don't know how to select a value in the SQL table as a float rather than a list, or how to convert a list into a float (is that even possible?). How do I proceed with the question and ultimately get it so that I can represent my cash value as a float to satisfy the if statement with the inequality? Help is much appreciated - thanks!

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock."""

    if request.method == "POST":

        if not request.form.get("symbol"):
            return apology("must enter stock symbol")

        shares = int(request.form.get("shares"))

        if not shares:
            return apology("must enter number of shares")

        cash = db.execute("SELECT cash FROM users WHERE id = 1")

        stock = lookup(request.form.get("symbol"))
        name = stock['name']
        symbol = stock['symbol']
        price = stock['price']

        if cash > shares*price:
            transaction = db.execute("INSERT INTO transactions (user, stock, price) VALUES ('insert user', symbol, cash)")

    else:
        return render_template("buy.html")

    return apology("TODO")
2
  • so how did you turn it into the float exactly?
    – jodelat
    Mar 23 '17 at 7:01
  • cash = (db.execute("SELECT * FROM users WHERE id = :id", id = session["user_id"]))[0]["cash"]
    – Ethan Teo
    Mar 24 '17 at 19:18
2

it seems like when I select the cash value from my SQL table, it is producing a list

Quite true. From the Hints section of the spec:

If str is a SELECT, then execute returns a list of zero or more dict objects, inside of which are keys and values representing a table’s fields and cells, respectively.

3
  • So I previously also tried using indices to access objects in the list, but as you said, they are dict objects. How am I supposed to access the values within the dict objects?
    – Ethan Teo
    Feb 20 '17 at 18:14
  • The usual way? cash[index][key] (in this case cash[0]["cash"]) Feb 20 '17 at 19:11
  • Oops - makes sense, thanks!
    – Ethan Teo
    Feb 21 '17 at 1:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .