在 HTML 中输入并在 python 中分析数学方程式
Taking Input in HTML and analyzing it in python for math equations
我有 python 中的这段代码,它随机生成一个数学方程式并检查用户答案 1 分钟:
import random
import time
correct=0
wrong=0
def random_problem(num_operations):
eq = str(random.randint(1, 100))
for _ in range(num_operations):
eq += random.choice(["+"])
eq += str(random.randint(1, 100))
return eq
start = time.time()
while True:
elapsed = time.time() - start
if elapsed > 60:
quotient=correct/wrong
precent=quotient*10
total_questions=correct+wrong
print(correct,"Correct",wrong,"Wrong, total questions",total_questions)
break
problem = random_problem(1)
ask=int(input(problem +": "))
solution = eval(problem)
if ask == solution:
correct=correct+1
print("Correct")
else:
wrong=wrong+1
print("Wrong, the correct answer is",solution)
我想知道是否可以将其从控制台转到 UI。我和使用烧瓶。谢谢
Flask 服务器很适合这个。 Flask 中的代码应该是这样的:
@ app.route('/', methods=['GET', 'POST'])
def home():
if request.method == "POST":
num = request.form['num']
# Check num if it is correct, use your code
# result is the data you will want to save
open_file('data.json', "w", result)
# math is your example
return render_template("index.html", math=math)
为了保存,我使用了我的 open_file () 函数,它看起来像这样:
def open_file(name, mode="r", data=None):
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, name)
if mode == "r":
with open(file_path, mode, encoding='utf-8') as f:
data = json.load(f)
return data
elif mode == "w":
with open(file_path, mode, encoding='utf-8') as f:
json.dump(data, f)
在html中,输入表单应该是这样的:
<form method = "POST" >
<input name = "text" type = "text">
<input name = "num" type = "number">
<button> submit </button>
</form>
你的数学例子是这样的:
<h1>{{math}}</h1>
我可能会建议在 javascript 中在网络上制作一个计时器,我认为在 flask 中它可能不起作用
我使用了我的 github 存储库中的所有内容:https://github.com/adammaly004/Online_fridge
希望对你有所帮助,亚当
保存数据有点难以理解你的意思。有几种不同的方式来存储数据。选择的变体取决于数据及其用途。
您可以在 request.form
对象中找到 Flask 表单中的数据,只要它是使用 POST 方法发送的。输入框的name属性决定了你可以在哪个下请求服务器上的数据。
下面的示例向您展示了如何在 Flask 中实现代码的可能解决方案。它应该作为您开发自己的解决方案或自行扩展的起点。
为了避免 eval
函数,使用了 dict
并填充了 operator
module. The result of the generated task is then calculated and saved in the session cookie.
中必要的运算符和函数
如果用户输入结果或让时间流逝,输入将与会话的结果进行比较。
时间限制由 JavaScript timeout 设置,时间一到就会自动提交表单。
烧瓶 (app.py)
from flask import Flask
from flask import render_template, request, session
from operator import add, sub
import random
app = Flask(__name__)
app.secret_key = 'your secret here'
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# Get the user input and convert it to an integer.
# If no entry is made, the default value 0 is returned.
r = request.form.get('r', 0, type=int)
# Check the result and choose a message depending on it.
msg = (
'Ooops, wrong result.',
'Yeah, you are right.'
)[int(r == session.get('r'))]
# This is the mapping of the operators to the associated function.
ops = { '+': add, '-': sub }
# Generate the task and save the result in the session.
op = random.choice(list(ops.keys()))
a = random.randint(1,100)
b = random.randint(1,100)
session['r'] = ops[op](a,b)
# Render the page and deliver it.
return render_template('index.html', **locals())
HTML (templates/index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Index</title>
</head>
<body>
{% if msg -%}
<p>{{msg}}</p>
{% endif -%}
<form name="task" method="post">
<span>{{a}} {{op}} {{b}} = </span>
<input type="number" name="r" />
<input type="submit">
</form>
<script type="text/javascript">
(function() {
// Submit the form automatically after the time has elapsed.
setTimeout(function() {
document.querySelector('form[name="task"]').submit();
}, 10000)
})();
</script>
</body>
</html>
我有 python 中的这段代码,它随机生成一个数学方程式并检查用户答案 1 分钟:
import random
import time
correct=0
wrong=0
def random_problem(num_operations):
eq = str(random.randint(1, 100))
for _ in range(num_operations):
eq += random.choice(["+"])
eq += str(random.randint(1, 100))
return eq
start = time.time()
while True:
elapsed = time.time() - start
if elapsed > 60:
quotient=correct/wrong
precent=quotient*10
total_questions=correct+wrong
print(correct,"Correct",wrong,"Wrong, total questions",total_questions)
break
problem = random_problem(1)
ask=int(input(problem +": "))
solution = eval(problem)
if ask == solution:
correct=correct+1
print("Correct")
else:
wrong=wrong+1
print("Wrong, the correct answer is",solution)
我想知道是否可以将其从控制台转到 UI。我和使用烧瓶。谢谢
Flask 服务器很适合这个。 Flask 中的代码应该是这样的:
@ app.route('/', methods=['GET', 'POST'])
def home():
if request.method == "POST":
num = request.form['num']
# Check num if it is correct, use your code
# result is the data you will want to save
open_file('data.json', "w", result)
# math is your example
return render_template("index.html", math=math)
为了保存,我使用了我的 open_file () 函数,它看起来像这样:
def open_file(name, mode="r", data=None):
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, name)
if mode == "r":
with open(file_path, mode, encoding='utf-8') as f:
data = json.load(f)
return data
elif mode == "w":
with open(file_path, mode, encoding='utf-8') as f:
json.dump(data, f)
在html中,输入表单应该是这样的:
<form method = "POST" >
<input name = "text" type = "text">
<input name = "num" type = "number">
<button> submit </button>
</form>
你的数学例子是这样的:
<h1>{{math}}</h1>
我可能会建议在 javascript 中在网络上制作一个计时器,我认为在 flask 中它可能不起作用
我使用了我的 github 存储库中的所有内容:https://github.com/adammaly004/Online_fridge
希望对你有所帮助,亚当
保存数据有点难以理解你的意思。有几种不同的方式来存储数据。选择的变体取决于数据及其用途。
您可以在 request.form
对象中找到 Flask 表单中的数据,只要它是使用 POST 方法发送的。输入框的name属性决定了你可以在哪个下请求服务器上的数据。
下面的示例向您展示了如何在 Flask 中实现代码的可能解决方案。它应该作为您开发自己的解决方案或自行扩展的起点。
为了避免 eval
函数,使用了 dict
并填充了 operator
module. The result of the generated task is then calculated and saved in the session cookie.
中必要的运算符和函数
如果用户输入结果或让时间流逝,输入将与会话的结果进行比较。
时间限制由 JavaScript timeout 设置,时间一到就会自动提交表单。
烧瓶 (app.py)
from flask import Flask
from flask import render_template, request, session
from operator import add, sub
import random
app = Flask(__name__)
app.secret_key = 'your secret here'
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# Get the user input and convert it to an integer.
# If no entry is made, the default value 0 is returned.
r = request.form.get('r', 0, type=int)
# Check the result and choose a message depending on it.
msg = (
'Ooops, wrong result.',
'Yeah, you are right.'
)[int(r == session.get('r'))]
# This is the mapping of the operators to the associated function.
ops = { '+': add, '-': sub }
# Generate the task and save the result in the session.
op = random.choice(list(ops.keys()))
a = random.randint(1,100)
b = random.randint(1,100)
session['r'] = ops[op](a,b)
# Render the page and deliver it.
return render_template('index.html', **locals())
HTML (templates/index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Index</title>
</head>
<body>
{% if msg -%}
<p>{{msg}}</p>
{% endif -%}
<form name="task" method="post">
<span>{{a}} {{op}} {{b}} = </span>
<input type="number" name="r" />
<input type="submit">
</form>
<script type="text/javascript">
(function() {
// Submit the form automatically after the time has elapsed.
setTimeout(function() {
document.querySelector('form[name="task"]').submit();
}, 10000)
})();
</script>
</body>
</html>