我想從一個有很多問題的網路 API 中得到 10 個隨機問題,但我似乎沒有讓它起作用。現在我得到KeyError: 'prompt',但我不知道該功能是否正確,因為我一直在嘗試一些不同的選項。
我還試圖在最后列印出您出錯的問題,但也沒有運氣。
import random
import requests
from random import randint
url = ""
the_questions = requests.get(url).json()
print("------ Welcome to Python quiz ------")
def random_question():
data = the_questions['prompt']
random_index = randint(0, len(data)-1)
return data[random_index]['prompt']
def get_correct_answers(answers):
res = []
for ans in answers:
if ans['correct']:
res.append(ans['answer'])
return res
def get_numeric(prompt, max_value,):
while True:
try:
res = int(input(prompt))
except ValueError:
print("Answer only with a number!")
continue
if 0 < res < max_value:
break
else:
print("Invalid answer option!")
return res
def main():
score = 0
for questions in the_questions['questions']:
#print(questions['prompt'])
print(random_question())
for i, a in enumerate(questions['answers'], start=1):
print(f"[{i}] {a['answer']}")
user_answer = get_numeric("> ", len(questions['answers']) 1)
if questions['answers'][user_answer - 1]['correct']:
score = 1
print(f"Right!")
else:
all_correct = ", ".join(get_correct_answers(questions['answers']))
print(f"Wrong, right is: {all_correct}")
print(f"You got {score} points of {len(the_questions['questions'])} possible!")
if __name__ == '__main__':
main()
API 示例
{"questions":[{"id":"1","prompt":"Which functions is used to write out text in the terminal?","answers":[{"answer":"print","correct":true},{"answer":"input","correct":false},{"answer":"import","correct":false},{"answer":"sys.exit","correct":false}]}
uj5u.com熱心網友回復:
錯誤顯示密鑰有問題,prompt您僅在random_question().
如果您使用print()查看變數中的值,random_question()那么您將看到您需要
data = the_questions['questions']
代替
data = the_questions['prompt']
至于我的變數名稱是誤導性的。您應該data對來自 API 的所有資訊使用 name ,然后才有questions = data['questions']意義。
編輯:
我的版本與 random.shuffle()
import random
#import requests
import json
def get_correct_answers(answers):
res = []
for ans in answers:
if ans['correct']:
res.append(ans['answer'])
return res
def get_numeric(prompt, max_value,):
while True:
try:
res = int(input(prompt))
except ValueError:
print("Answer only with a number!")
continue
if 0 < res < max_value:
break
else:
print("Invalid answer option!")
return res
def main():
print("------ Welcome to Python quiz ------")
#url = ""
#data = requests.get(url).json()
data = json.loads('''
{"questions":[
{"id":"1","prompt":"Which functions is used to write out text in the terminal?","answers":[{"answer":"print","correct":true},{"answer":"input","correct":false},{"answer":"import","correct":false},{"answer":"sys.exit","correct":false}]},
{"id":"2","prompt":"Which functions is used to read text from the terminal?","answers":[{"answer":"print","correct":false},{"answer":"input","correct":true},{"answer":"exec","correct":false},{"answer":"load","correct":false}]}
]}
''')
questions = data['questions']
random.shuffle(questions)
score = 0
for question in questions:
print(question['prompt'])
answers = question['answers']
for i, a in enumerate(question['answers'], 1):
print(f"[{i}] {a['answer']}")
user_answer = get_numeric("> ", len(answers) 1)
if answers[user_answer-1]['correct']:
score = 1
print(f"Right!")
else:
all_correct = ", ".join(get_correct_answers(answers))
print(f"Wrong, right is: {all_correct}")
print(f"You got {score} points of {len('questions')} possible!")
if __name__ == '__main__':
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/322307.html
上一篇:如何編號Elm中的串列元素?
下一篇:拆分串列中的值并創建2個新串列
