Когда я пытаюсь запустить этот код, кажется, что все работает, но при получении окончательной оценки я ее не получаю, поскольку она отображается пустой.
#!/usr/bin/env python3
import json #this is to load the files of from the target folder
import time
import turtle
TOPICS_LIST = ['General_Questions', 'Disciplines', 'Studies', 'Psychology', 'Theories']
# this list has to in sync with the JSON filename and the Menu prompt inside test() method
def quiz_main():
turtle.clear()
turtle.hideturtle()
turtle.penup()
screen = turtle.Screen()
screen.setup(1000,600)
screen.colormode(255)
screen.bgcolor(255, 255, 255)
def ask_one_question(question):
quiz_main()
turtle.goto(-400, 50)
turtle.write("\n" + question, font=('Courier', 20, 'bold'))
time.sleep(1)
choice = str(turtle.textinput("Enter Your Choice [a/b/c/d]: ", "Answer"))
while(True):
if choice.lower() in ['a', 'b', 'c', 'd']:
return choice
else:
turtle.write("Incorrect choice. Please try again", font=('Courier', 20, 'italic'))
choice = str(turtle.textinput("Enter Your Choice [a/b/c/d]: ", "Answer"))
def score_one_result(key, meta):
quiz_main()
turtle.goto(-300, 100)
actual = meta["answer"]
if meta["user_response"].lower() == actual.lower():
return 2
else:
return -1
def test(questions):
quiz_main()
turtle.goto(-450, -100)
score = 0
turtle.write("Please read the instructions:\n1. Please enter only your choice letter corresponding to your answer.\n2. Each question has 2 points\n3. A wrong answer will give -1 \n The Quiz will start shortly.\n Good Luck!\n", font=('Courier', 15, 'bold'))
time.sleep(10)
quiz_main()
turtle.goto(-400, -100)
for key, meta in questions.items():
questions[key]["user_response"] = ask_one_question(meta["question"])
quiz_main()
turtle.goto(-200, 0)
for key, meta in questions.items():
score += score_one_result(key, meta)
turtle.write("Your Final Score:", score, font=('Courier', 30, 'bold'))
turtle.exitonclick()
def load_question(filename):
"""
loads the questions from the JSON file into a Python dictionary and returns it
"""
questions = None
with open(filename, "r") as read_file:
questions = json.load(read_file)
return (questions)
def play_quiz():
quiz_main()
turtle.goto(-300, -50)
flag = False
try:
turtle.write("Thank you for taking Our Simple Quiz!\nChoose which one is your interest:\n(1). General Questions\n(2). Disciplines\n(3). Studies\n(4). Psychology\n(5). Theories\nEnter Your Choice [1/2/3/4/5]: ", font=('Courier', 20, 'bold'))
time.sleep(5)
choice = int(turtle.textinput("Topic", "Topic"))
if choice > len(TOPICS_LIST) or choice < 1:
print("Invalid Choice. Try Again")
flag = True # raising flag
except ValueError as e:
print("Invalid Choice. Try Again")
flag = True # raising a flag
if not flag:
questions = load_question('c:/Quiz Game/topics/'+TOPICS_LIST[choice-1]+'.json')
test(questions)
else:
play_quiz() # replay if flag was raised
def user_begin_prompt():
quiz_main()
turtle.goto(-200, 0)
turtle.write("Simple Quiz Game", font=('Courier', 30, 'bold'))
time.sleep(5)
play = turtle.textinput("Shall we try?\nA. Yes\nB. No", "A or B")
if play.lower() == 'a' or play.lower() == 'y':
play_quiz()
elif play.lower() == 'b':
print("Hope you come back soon!")
else:
print("Hmm. I didn't quite understand that.\nPress A to play, or B to quit.")
user_begin_prompt()
def execute():
user_begin_prompt()
if __name__ == '__main__':
execute()
Я уже пробовал изменить переменную на str или int, но та же проблема. есть файл JSON, в котором вопросы правильно отформатированы и работают без проблем. код работает на 90 %, но не отображается только итоговая оценка.
Я надеюсь показать окончательную оценку пользователя, выполняющего этот тест.
вот json-код тем:
{
"1": {
"question": "What is the main focus of the HUMSS strand?\n(a) Computer Science\n(b) Humanities and Social Sciences\n(c) Information Technology\n(d) Coding\n",
"answer": "b",
"more_info": "None",
"user_response": "None"
},
}
это школьный проект, над которым мы с одноклассниками работаем, чтобы мы могли пройти наш компьютерный класс. Спасибо за вашу помощь. Я просто новичок в Python.
Когда я пытаюсь запустить этот код, кажется, что все работает, но при получении окончательной оценки я ее не получаю, поскольку она отображается пустой. [code]#!/usr/bin/env python3 import json #this is to load the files of from the target folder import time import turtle
TOPICS_LIST = ['General_Questions', 'Disciplines', 'Studies', 'Psychology', 'Theories'] # this list has to in sync with the JSON filename and the Menu prompt inside test() method
def score_one_result(key, meta): quiz_main() turtle.goto(-300, 100) actual = meta["answer"] if meta["user_response"].lower() == actual.lower(): return 2 else: return -1
def test(questions): quiz_main() turtle.goto(-450, -100) score = 0 turtle.write("Please read the instructions:\n1. Please enter only your choice letter corresponding to your answer.\n2. Each question has 2 points\n3. A wrong answer will give -1 \n The Quiz will start shortly.\n Good Luck!\n", font=('Courier', 15, 'bold')) time.sleep(10) quiz_main() turtle.goto(-400, -100) for key, meta in questions.items(): questions[key]["user_response"] = ask_one_question(meta["question"]) quiz_main() turtle.goto(-200, 0) for key, meta in questions.items(): score += score_one_result(key, meta) turtle.write("Your Final Score:", score, font=('Courier', 30, 'bold')) turtle.exitonclick()
def load_question(filename): """ loads the questions from the JSON file into a Python dictionary and returns it """ questions = None with open(filename, "r") as read_file: questions = json.load(read_file) return (questions)
def play_quiz(): quiz_main() turtle.goto(-300, -50) flag = False try: turtle.write("Thank you for taking Our Simple Quiz!\nChoose which one is your interest:\n(1). General Questions\n(2). Disciplines\n(3). Studies\n(4). Psychology\n(5). Theories\nEnter Your Choice [1/2/3/4/5]: ", font=('Courier', 20, 'bold')) time.sleep(5) choice = int(turtle.textinput("Topic", "Topic")) if choice > len(TOPICS_LIST) or choice < 1: print("Invalid Choice. Try Again") flag = True # raising flag except ValueError as e: print("Invalid Choice. Try Again") flag = True # raising a flag if not flag: questions = load_question('c:/Quiz Game/topics/'+TOPICS_LIST[choice-1]+'.json') test(questions) else: play_quiz() # replay if flag was raised
def user_begin_prompt(): quiz_main() turtle.goto(-200, 0) turtle.write("Simple Quiz Game", font=('Courier', 30, 'bold')) time.sleep(5) play = turtle.textinput("Shall we try?\nA. Yes\nB. No", "A or B") if play.lower() == 'a' or play.lower() == 'y': play_quiz() elif play.lower() == 'b': print("Hope you come back soon!") else: print("Hmm. I didn't quite understand that.\nPress A to play, or B to quit.") user_begin_prompt()
def execute(): user_begin_prompt()
if __name__ == '__main__': execute() [/code] Я уже пробовал изменить переменную на str или int, но та же проблема. есть файл JSON, в котором вопросы правильно отформатированы и работают без проблем. код работает на 90 %, но не отображается только итоговая оценка. Я надеюсь показать окончательную оценку пользователя, выполняющего этот тест. вот json-код тем: [code]{ "1": { "question": "What is the main focus of the HUMSS strand?\n(a) Computer Science\n(b) Humanities and Social Sciences\n(c) Information Technology\n(d) Coding\n", "answer": "b", "more_info": "None", "user_response": "None" }, } [/code] это школьный проект, над которым мы с одноклассниками работаем, чтобы мы могли пройти наш компьютерный класс. Спасибо за вашу помощь. Я просто новичок в Python.
Когда я пытаюсь запустить этот код, кажется, что все работает, но при получении окончательной оценки я ее не получаю, поскольку она отображается пустой.
#!/usr/bin/env python3
import json #this is to load the files of from the target folder
import...
Я хочу показать на экране текущий счет игрового процесса и Storical Best Score.
Это работа, но каждый раз я перезагружаю игру лучшее изменение результата, даже если текущий счет ниже, чем лучший результат.
Я хочу показать на экране текущий счет игрового процесса и Storical Best Score.
Это работа, но каждый раз я перезагружаю игру лучшее изменение результата, даже если текущий счет ниже, чем лучший результат.
Я делаю функцию draw_square, которая рисует квадрат с помощью черепахи. Требуется (t, side_length), где t - имя черепахи, а side_length - это длина бокового. Однако при тестировании в Thonny с использованием drain_square (Dave, 50) он говорит, что...