簡體   English   中英

二次方程與 Python 和 Flask

[英]Quadratic Equation with Python and Flask

所以目前我正在嘗試使用 flask 制作一個程序,但是當我運行它時出現TypeError ,說The view function for 'post_factors' did not return a valid response. The function either returned None or ended without a return statement. The view function for 'post_factors' did not return a valid response. The function either returned None or ended without a return statement. 我不知道如何解決它。 這是代碼:

import math

def dofactors(a, b, c):
    a = int(a)
    b = int(b)
    c = int(c)
    d = b**2-4*a*c # discriminant

    if d < 0:
        result = 'No solutions'
    elif d == 0:
        x1 = -b / (2*a)
        result = f'The sole solution is {str(x1)}'
    else: # if d > 0
        x1 = (-b + math.sqrt(d)) / (2*a)
        x2 = (-b - math.sqrt(d)) / (2*a)
        result = f'Solutions are {str(x1)} and {str(x2)}'

    return(result)

和 HTML:

<!DOCTYPE html>
<form method="POST">
  <p><h1>Factorizer</h1></p>
    <p>please enter your variable values assuming the form ax^2+bx+c</p>
  <input type="text", placeholder="a", name="a" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '$1');" />
  <input type="text", placeholder="b", name="b" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '$1');" />
  <input type="text", placeholder="c", name="c" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '$1');" />
  <input type="submit">
</form>

編輯:我忘了在主 class 中包含調用它的代碼,這里是:

@app.route('/factors')
def form_factors():
    return render_template('factors.html')

和 POST function:

@app.route('/factors', methods=['POST'])
def post_factors():
    a = str(request.form['a'])
    b = str(request.form['b'])
    c = str(request.form['c'])
    dofactors(a, b, c)

您在dofactor function 中返回值,但這些“返回”不適用於路由,因為它們在不同的 scope 中。您可以在post_factors路由中使用以下內容解決此問題。

return(dofactors(a, b, c))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM