You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

哈佛CS50 Finance项目Buy函数check50报错求助

CS50 Finance项目Buy功能Check50错误修复求助

问题现象

代码能正常处理合法买入订单,但check50返回以下错误:

:( buy handles fractional, negative, and non-numeric shares
    application raised an exception (see the log for more details)
:( buy handles valid purchase
    expected to find "112.00" in page, but it wasn't found

相关代码

Python后端代码

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""
    if request.method == "GET":
        return render_template("buy.html")
    else:
        symbol = request.form.get("symbol")
        shares = int(request.form.get("shares"))

        if not symbol:
            return apology("Must provide ticker")

        stock = lookup(symbol.upper())

        if stock == None:
            return apology("Ticker does not exist")

        if shares < 1:
            return apology("Minimum purchase is 1 share")

        transaction_value = shares * stock["price"]

        user_id = session["user_id"]
        user_cash_db = db.execute("SELECT cash FROM users WHERE id = :id", id=user_id)
        user_cash = user_cash_db[0]["cash"]

        if user_cash < transaction_value:
            return apology("Not enough funds available")

        uptd_cash = user_cash - transaction_value

        # update the SQL database
        db.execute("UPDATE users SET cash = ? WHERE id = ?", uptd_cash, user_id)

        date = datetime.datetime.now()

        db.execute("INSERT INTO transactions (user_id, symbol, shares, price, date) VALUES (?, ?, ?, ?, ?)", user_id, stock["symbol"], shares, stock["price"], date)

        flash("Bought!")

        # redirect to main page
        return redirect("/")

HTML前端代码

{% extends "layout.html" %}

{% block title %}
    Buy
{% endblock %}

{% block main %}
    <h1>Buy</h1>
    <form action="/buy" method="post">
        <div class="mb-3">
            <input autocomplete="off" autofocus class="form-control mx-auto w-auto" name="symbol" placeholder="Ticker" type="text">
        </div>
        <div class="mb-3">
            <input autocomplete="off" autofocus class="form-control mx-auto w-auto" name="shares" placeholder="Shares" type="number">
        </div>
        <button class="btn btn-primary" type="submit">Buy</button>
    </form>
{% endblock %}

已尝试的方法

曾尝试用isdigit()替代强制转int,但在验证份额为正整数时出现逻辑冲突,导致代码崩溃。


解决方案

1. 修复"处理小数、负数、非数字份额时抛出异常"的问题

问题根源:直接执行int(request.form.get("shares"))时,若输入非整数(如小数、字符串)会抛出ValueError,导致应用崩溃。需先验证输入合法性,再安全转换。

修改后的后端代码:

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""
    if request.method == "GET":
        return render_template("buy.html")
    else:
        symbol = request.form.get("symbol")
        shares_str = request.form.get("shares")

        # 基础输入校验
        if not symbol:
            return apology("Must provide ticker")
        if not shares_str:
            return apology("Must provide number of shares")
        
        # 安全转换并验证份额为正整数
        try:
            shares = int(shares_str)
            if shares < 1:
                raise ValueError
        except ValueError:
            return apology("Shares must be a positive integer")

        stock = lookup(symbol.upper())
        if stock is None:
            return apology("Ticker does not exist")

        # 后续交易逻辑保持不变
        transaction_value = shares * stock["price"]
        user_id = session["user_id"]
        user_cash_db = db.execute("SELECT cash FROM users WHERE id = :id", id=user_id)
        user_cash = user_cash_db[0]["cash"]

        if user_cash < transaction_value:
            return apology("Not enough funds available")

        uptd_cash = user_cash - transaction_value
        db.execute("UPDATE users SET cash = ? WHERE id = ?", uptd_cash, user_id)
        db.execute("INSERT INTO transactions (user_id, symbol, shares, price, date) VALUES (?, ?, ?, ?, ?)",
                   user_id, stock["symbol"], shares, stock["price"], datetime.datetime.now())

        flash("Bought!")
        return redirect("/")

修改说明:

  • 先获取份额的原始字符串值,避免直接转换抛出异常
  • 用try-except捕获转换错误,同时验证份额必须≥1,所有非法输入都会返回友好提示而非崩溃
  • 将stock == None改为Python推荐的stock is None写法

2. 修复"未找到'112.00'格式金额"的问题

问题根源:主页(/)未将用户现金余额格式化为两位小数的货币格式,check50期望匹配112.00这类带两位小数的字符串。

检查主页模板(如index.html)中显示现金的部分,确保使用CS50提供的usd过滤器格式化:

<!-- 示例:主页中显示现金的代码 -->
<div>
    Cash: {{ cash | usd }}
</div>

usd过滤器会自动将数值格式化为两位小数的字符串(如112变为112.00),满足check50的格式要求。


内容的提问来源于stack exchange,提问作者Papyrus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 15:00:43