R
R
realgord882015-01-30 12:59:53
Flask
realgord88, 2015-01-30 12:59:53

Why doesn't counter work in Python/Flask?

There is a page on Python/Flask. The user must enter the correct answer to multiply the two numbers and the score counter must increase by 1. But unfortunately it doesn't work. Tell me please. There is a screen.

from flask import render_template, flash, redirect
from app import app
from forms import LoginForm
import random
import time

counter = 0

@app.route('/', methods = ['GET', 'POST'])
@app.route('/index', methods = ['GET', 'POST'])
def index():
    numb = 0
    answer = 0
    first = 0
    second = 0
    global counter
    form = LoginForm()
    first = random.randint(1, 10)
    second = random.randint(1, 10)
    answer = first*second
    if form.validate_on_submit():
        numb = int(form.answer.data)
        if numb == answer:
            counter += 1
            return redirect('/index')
        else:
            counter = 0
            return redirect('/index')
    return render_template("index.html",
        first = first,
        second = second,
        form = form,
        numb = numb,
        answer = answer,
        counter = counter)


Snippet from HTML
<h2><p align="center">{{first}}*{{second}}=</p></h2>

<form action="" method="post" name="answer">
    {{form.hidden_tag()}}
        <p align="center">{{form.answer(size=40)}}  <input type="submit" value="Ответить"></p>
        <p align="center">Счет: {{counter}}</p><br>


5ee5a065935d425c95a02ea2d5bbd877.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Kobyshev, 2015-01-30
@realgord88

Your program logic is not working. :) You think the answer is wrong. What is this?

first = random.randint(1, 10)
second = random.randint(1, 10)
answer = first*second

You generate first and second randomly and show it to the user. The user enters a response. On the next request, you randomly generate them again (instead of taking the ones the user has dealt with) and check the product of the new ones with what the user entered (and there the product of the old ones). Naturally, the counter will increase with the same probability as the elephant flies outside the window. :)
In general, if you do it right, then start a session for the user (for example, flask-beaker) and save the results there (including the answer, which is expected from the previous step). Otherwise, with the number of users > 1 per application, you will again have bugs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question