Flask / jinja如何计算平均值



我正在尝试学习jinja/flash/python组合,但有问题。我从互联网上找到了这种例子,让它工作得很好,但现在我想改进代码,不知道如何。我尝试了很多不同的操作来打印用户给出的分数的平均值,但是都没有成功。

有人知道怎么帮忙吗?

grades.html

<form action = "result" method = "POST">
<p>Name <input type = "text" name = "Name" /></p>
<p>Gymnastics <input type = "text" name = "Gymnastics" /></p>
<p>English <input type = "text" name = "English" /></p>
<p>Maths <input type ="text" name = "Maths" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>

result.html

<!doctype html>
<table border = 1>
{% for key, value in result.items() %}

<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}

</table>

app.py

from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def student():
return render_template('grades.html')

@app.route('/result',methods = ['POST', 'GET'])
def result():
if request.method == 'POST':
result = request.form
return render_template("result.html",result = result)

好的,所以它工作得很好,但是我如何改进我的代码并打印所有这些张贴的成绩的平均值?

要计算成绩,将它们相加并除以成绩数。或者您可以使用statistics.mean()函数:

import statistics
@app.route('/result',methods = ['POST', 'GET'])
def result():
subjects = ['Gymnastics', 'English', 'Maths']
if request.method == 'POST':
result = request.form.to_dict()
average = statistics.mean([float(result[subject]) for subject in subjects])
result['average'] = f'{average:.2f}'
return render_template("result.html",result = result)

此代码提取每个已知科目的成绩并将其转换为浮点值。计算平均值,将其转换为小数点后2位的字符串,并放入result字典中,以便在模板中可用。

模板将显示结果,但是,您可能希望将其格式化得更好。

最新更新