CS50s finance - stuck at : buy handles valid purchase
10:32 07 Oct 2026

Cause
expected to find "112.00" in page, but it wasn't found

Log

sending POST request to /login
sending POST request to /buy
sending POST request to /buy
checking that "112.00" is in page

Unfortunately I can not reproduce the error, but get valid output in my own testing. Also the duck debugger does not help to find the issue.

I already tried around with the usd-format in different places and after some research ended up rounding my numbers to not get some mistakes within the process. That seems not to be the issue. Maybe sb can help :)

Routes for buy and index look like this:

@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""

    user_id = session["user_id"]
    cash_raw = db.execute(
        "SELECT cash FROM users WHERE id=?", user_id
    )
    if not cash_raw:
        return apology("No cash found")
    cash = round(float(cash_raw[0]["cash"]), 2)
    value = 0.0
    table = []

    shares = db.execute(
        "SELECT symbol, share_count FROM shares where id = ? AND share_count > 0 ORDER BY symbol", user_id
    )
    for share in shares:
        symbol = share["symbol"]
        share_count = int(share["share_count"])

        search = lookup(symbol)
        if search:
            price = round(float(search["price"]), 2)
            share_value = round(price * share_count, 2)

            line = {
                "symbol": symbol,
                "share_count": share_count,
                "price": price,
                "share_value": share_value
            }
            value += share_value
            table.append(line)

    total = round(cash + value, 2)

    return render_template("index.html", user_id=user_id, table=table, cash = cash, total = total)


@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""
    if request.method == "POST":
        symbol = request.form.get("symbol")
        shares_input = request.form.get("shares")
        if not symbol:
            return apology("must provide valid symbol", 400)
        if not shares_input:
            return apology("must provide number of shares", 400)
        try:
            shares = int(shares_input)
        except ValueError:
            return apology("shares must be whole number", 400)
        if shares <= 0:
                return apology("must provide positive number of shares", 400)

        result = lookup(symbol)
        if result is None:
            return apology("invalid symbol", 400)

        if update_balance(result, shares):
            shares_db(result, shares)
            purchase(result, shares)
            return redirect("/")
        else:
            return apology("not enough cash", 400)
    else:
        return render_template ("buy.html")

where shares-table in sql contains id, symbol, stock, share_count

and purchases-table (which should not be the issue as long as i dont get buying process to work) contains date and price.

My helpers are:

def update_balance(result, shares):
    """check if balance is enough to buy desired amount of shares."""
    user_id = session["user_id"]
    balance_db = db.execute(
        "SELECT cash FROM users WHERE id = ?", user_id
    )
    if not balance_db:
        return False

    balance = float(balance_db[0]["cash"])
    if balance >= float(result["price"]) * shares:
        new_balance = round(balance - (float(result["price"]) * shares), 2)
        db.execute(
            "UPDATE users SET cash = ? WHERE id = ?", new_balance, user_id
        )
        return True
    else:
        return False

def shares_db(result, shares):
    """Update table 'shares' within the db."""
    user_id = session["user_id"]
    shares = int(shares)
    symbol = result["symbol"].upper()

    # Frage die Anzahl an Aktienstämmen dieser Aktie dieses Users ab
    n_db = db.execute(
            "SELECT share_count as n FROM shares WHERE id = ? AND symbol = ?", user_id, symbol)
    if len(n_db) > 0:
        current_shares = int(n_db[0]["n"])
        new_shares = current_shares + shares
        db.execute("UPDATE shares SET share_count = ? WHERE id = ? AND symbol = ?", new_shares, user_id, symbol)
    else:
        db.execute("INSERT INTO shares (id, symbol, stock, share_count) VALUES (?, ?, ?, ?)", user_id, symbol, result["name"], shares)

Finally my index.html is:

{% extends "layout.html" %}

{% block title %}
Home
{% endblock %}

{% block main %}
{% for line in table %} {% endfor %}
Symbol Shares Price Total
{{ line["symbol"] }} {{ line["share_count"] }} {{ line["price"]|usd }} {{ line["share_value"]|usd }}
Cash {{ cash|usd }}
Total {{ total|usd }}
{% endblock %}

I know its not the most pythonic code possible, but as a beginner I hope to be able to work with it for this task.

I would be grateful for any advice as I dont even know why the expected value is not in check50s template.

python cs50