简体   繁体   中英

python how do I deal with unreachable code flask

I'm building a web app. My code stops after return statement. How do I keep the code running after the fact? Do I need something else besides flask? Thanks!

Here's my HTML code

<!DOCTYPE html>

<html>
<head>
    <title>THE QUIZ</title>
</head>

<body>
    <h1>QUIZ GAME</h1>

    <p>
        Welcome
    </p>

    <h2>Would you like to play</h2>

    <form action="/play" method="POST">
            Enter your answer: <input type="text" name="answers">
             <input type="submit" value="submit">
    </form>

</body>
</html>

here's my python code

@app.route("/")
def main():
    return render_template('app.html')

if request.method == 'POST':
        answers = request.form.get('answers')
        random.shuffle(questions.qa)
        response = quiz(qa, user1, answers)
    

        #this function asks the questions and stores them

    return render_template('app.html') + response

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)

Here's where I run into problems. It's the 2nd function. Once I get to iterate over the list and return the data in the list the code beneath the return statement becomes unreachable and the program stops doing what it's supposed to. How can I return data from the list and have the code continues with the if statements. I've searched but don't understand the results I've found since they're more complex and I'm new at using flask.

def quiz(qa, user, ans):
    for rand_q in qa:
        return rand_q['question']
        if 'yes' in ans:
            user.append('yes')
            return rand_q.get(ans, '') #this gets 2nd part of question

My if statement becomes unreachable therefore unable to return the second set of values from list of dict

Here's my modified code but I'm still stuck at returning the 2nd part of my list dict after the client's input.

def play():

    qa = questions.qa #list of dict with questions
    user1, user2 = [], [] #containers for each player's answers

    if request.method == 'POST':
        answers = request.form.get('answers')
        random.shuffle(questions.qa)
        response = quiz(qa, user1)

    return response 


def quiz(qa, user):
    for rand_q in qa:
        
        i = rand_q['question']
        i2 = check_answer(i, user)
        
    #print(rand_q["question"])
        return i2

@app.route("/", methods = ['POST', 'GET'])
def check_answer(ans, user):
    if request.method == 'POST':
        answers = request.form.get('answers')
        if 'yes' in answers:
            user.append('yes')
            i3 = ans.get(answers, '')
    return i3 #this should send 2nd part of question/rand_q

Python, as almost any other programming language, allows you to execute commands sequentially. Internally in the operating system the program, that python creates, is called a process. The commands are executed A then B then C and so on. Of course there are some commands that allow you to chose the flow of the commands: if A then B otherwise C. But there is still a sequence of commands that are executed sequentially.

Now what does the return statement do in python? Executing a function means that the function is called from some other code. Then the code of the function is executed and then the next commands in some other code are executed, that are after the function call. How do we know that this is the end of the function? This is the return statement. The function can only return one variable. As soon as you already set the return variable there is no need to wait for all the other code, because the return of the function will not change. So the function ends and returns what you have in return statement.

There are different ways how to circumvent this process, depending on what you want:

1.You want to return multiple things and it is ok for the processing of the result to wait until you have calculated all the results. In this case use a tuple or a list to return from the function. For example:

res = []
res.append(res1)
res.append(res2)
return res

2.You want to return one of the results as soon as it is available and start processing it in parallel to executing the code that follows.

In this case you are in the realm of parallel programming. You need a way to communicate between different parallel processes/threads. For example, you could use a queue:

import queue

q = queue.Queue()

def quiz(qa, user, ans, q):
    q.put(res1)
    q.put(res2)

def worker(q):
    while True:
        item = q.get()
        print(f'Working on {item}')

# turn-on the worker thread
threading.Thread(target=worker, args=(q,)).start()

In this case you do not need to use return and a separate thread is working on the items in a queue.

When I look at you question in more detail it seems that you want to have an ans after you execute the first return. This is not possible because inside of the function you cannot receive any additional information from the outside code, because the outside code is not executed (with an exception of parallel programming). What you really need is to have two functions. One chooses the question and another checks the answer:

def quiz(qa, user):
    return question

def check_answer(user, ans):
    if ans == 'yes':
        user.append('yes')
        return second_part_of_question

And the flow of the program should be:

  1. Send the user the question
  2. Get the answer from the user
  3. Send additional information based on the answer

Your code shares little information about how you do it in Flask, so I will just use an example with a console python app:

question1 = quiz(qa, user)
print(question1)
ans = input()
question2 = check_answer(user, ans)
print(question2)

The logic in Flask is the same, but it is implemented differently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM