我的Python测验游戏有问题,我真的不知道如何继续前进。这些问题来自一个API,我希望能够用一个数字来回答正确的问题是什么(我已经固定了,这样问题的替代有数字在他们前面)。我现在可以写出正确的答案,但不能用数字表示。当我写错误的答案或者答案与我取回整个字典是这样的:
Wrong, right answer is: [{'answer': 'print', 'correct': True}, {'answer': 'input', 'correct': False}, {'answer': 'import', 'correct': False}, {'answer': 'sys.exit', 'correct': False}]
我只是想要正确的答案,但我真的不知道如何解决这个问题。所以,我希望能够用一个数字来回答,然后得到正确的答案。我该如何解决这个问题?我试过在correct_answer = question['answers']的主函数中应用int(user_answer) - 1,但我不让它工作,所以也许这是错误的方法。
import requests
url = ""
the_questions = requests.get(url).json()
print("------ Welcome to Python Quiz ------")
def compare_answer(correct, answers):
return any(ca["correct"] and ca["answer"].strip().lower() == answers for ca in correct)
def get_correct_answers(answers):
res = []
for ans in answers:
if ans['correct']:
res.append(ans['answer'])
return res
def main():
score = 0
for question in the_questions['questions']:
print(question['prompt'])
for i, a in enumerate(question['answers'], start=1):
print(f"[{i}] {a['answer']}")
user_answer = input("> ")
correct_answer = question['answers']
if compare_answer(correct_answer, user_answer):
score += 1
print(f"Right!")
else:
print(f"Wrong, the right answer is: {correct_answer}")
print(f"You got {score} points out of 3!")
if __name__ == '__main__':
main()
这是API现在的样子,如果它有帮助的话。
{"questions":[{"id":"1","prompt":"Vilken funktion anvu00e4nder du fu00f6r att skriva ut text i terminalen?","answers":[{"answer":"print","correct":true},{"answer":"input","correct":false},{"answer":"import","correct":false},{"answer":"sys.exit","correct":false}]},{"id":"2","prompt":"Hur tar man fram lu00e4ngden pu00e5 listan i variabeln "fruits"?","answers":[{"answer":"for _ in range(10)","correct":false},{"answer":"input(fruits)","correct":false},{"answer":"len(fruits)","correct":true}]},{"id":"3","prompt":"Vad heter nyckelordet fu00f6r att gu00f6ra en loop i python?","answers":[{"answer":"in","correct":false},{"answer":"for","correct":true},{"answer":"while","correct":true}]}]}
get_correct_answers()
函数将返回正确的答案。调用它并显示结果
if compare_answer(correct_answer, user_answer):
score += 1
print(f"Right!")
else:
all_correct = ", ".join(get_correct_answers(correct_answer)
print(f"Wrong, the right answer is: {all_correct}")