SOMEONE_14_
SOMEONE_14_

Reputation: 35

Taking Input in HTML and analyzing it in python for math equations

I have this code that is in python and randomly makes a math equation and checks the user answer for 1 minute:

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)

I wanted to know if it is possible to make this go from the console onto a UI. I and using flask. Thanks

Upvotes: 0

Views: 462

Answers (2)

Detlef
Detlef

Reputation: 8582

It's a little hard to understand what you mean by saving the data. There are several different ways to store data. The variant to choose depends on the data and its use.

You can find data from a form in Flask in the request.form object as long as it was sent using the POST method. The name attribute of the input field determines under which you can request the data on the server.

The example below shows you a possible solution how to implement your code in Flask. It should serve as a starting point for you to develop your own solution or expand it on your own.

To avoid the eval function, a dict is used and filled with the necessary operators and functions from the operator module. The result of the generated task is then calculated and saved in the session cookie.
If the user enters a result or lets the time elapse, the input is compared with the result from the session.
The time limit is set by a JavaScript timeout, which automatically submits the form as soon as the time has elapsed.

Flask (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>

Upvotes: 1

adammaly004
adammaly004

Reputation: 231

Flask server is good for this. This is how the code in the flask should look like:

@ 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)

To save, I used my open_file () function, which looks like this:

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)

In html, the input form should look like this:

<form method = "POST" >
    <input name = "text" type = "text">
    <input name = "num" type = "number">
    <button> submit </button>
</form>

Your math example show like this:

<h1>{{math}}</h1>

I would probably recommend making a timer on the web in javascript, I think in flask it might not work

I used everything from my github repository: https://github.com/adammaly004/Online_fridge

I hope it will help you, Adam

Upvotes: 1

Related Questions