我试图为python测验编写一个函数,该函数将根据用户操作在字典中显示下一个键(名为" question")。我已经有了检查答案是否正确的功能,但我正在努力争取它然后显示下一个键(问题)。我也给了用户3次尝试解决问题所以下一个问题无法显示,除非a)问题得到解答或b)他们用完了猜测。
我已经玩了for循环和while循环,但我似乎能够做的就是一遍又一遍地重复同样的事情。我应该使用范围参数还是其他什么?
riddles=[]
with open("data/riddles.json") as riddles_file:
riddles = json.load(riddles_file)
def right_answer(answer, riddle):
return answer == riddle["answer"]
def next_question(riddles):
for riddle in riddles:
#run the first question. If question correct, run the next question.
app = Flask(__name__)
app.secret_key = 'some_secret'
@app.route('/<user>', methods = ['GET', 'POST'])
def quiz(user):
riddle = riddles[0]
#hard coded to show first question
max_guesses = 3
counter = 0
if request.method == "POST":
answer = request.form.get("answer")
while counter < max_guesses:
if right_answer(answer, riddle):
game_status[user] += 1
next_question(riddles)
return render_template("user.html", user=user, score=game_status[user], question=riddle["question"], message = "Correct. Well done!")
else:
counter += 1
guesses_left = max_guesses - counter
print("answer")
return render_template("user.html", user=user, score=game_status[user], question=riddle["question"], message = "This is wrong. Try again. Your remaining guesses are:", guesses = guesses_left, answer = answer)
return render_template("user.html", user=user, score=game_status[user], question=riddle["question"] )
答案 0 :(得分:0)
我的方式:测验会有一个riddle_number参数,默认设置为0
def quiz(user, riddle_number=0):
riddle = riddles[riddle_number]
你的测试时间不好:它只适用于失败。而是创建一个标志
next_riddle = False
while not next_riddle:
if right_answer(answer, riddle):
next_riddle = True
[...]
else:
guesses_left = max_guesses - counter
if guesses_left == 0:
next_riddle = True
[...]
然后我用riddle_number+1