Перед тем как продолжить, убедитесь, что у вас есть следующие предварительные условия:
- Python3 установлен
- Предпочтительная IDE (я использую Pycharm)
Шаг 1. Создайте файл с именем data.py, который будет содержать словарь под названием question_data, в котором будут храниться все вопросы и ответы на них.
question_data = [{ "question": "AWS is more economical than traditional data centers for applications with varying compute workloads because Amazon EC2 instances can be launched on demand when needed.","answer": "True"}, {"question": "AWS Storage Gateway helps migrate databases to AWS quickly and securely.", "answer": "False"}, { "question": "AWS FleaMarket is a digital catalog with thousands of software listings from independent software vendors that makes it easy to find, test, buy, and deploy software that runs on AWS.", "answer": "False"}, {"question": "Amazon VPC lets users provision a logically isolated section of the AWS Cloud where users can launch AWS resources in a virtual network that they define.","answer": "True"}, {"question": "Maintaining physical hardware is an AWS responsibility under the AWS shared responsibility model.","answer": "True"}, {"question": "To deliver content to users with lower latency, Amazon CloudFront uses a global network of points of presence (edge locations and regional edge caches) worldwide.","answer": "True"}, {"question": "Multi-Factor Authentication adds an additional layer of login security to a user's AWS Management Console.", "answer": "True"}, {"question": "AWS X-Ray can identify the user that made the API call when an Amazon EC2 instance is terminated.","answer": "False"}, {"question": "Amazon Simple Notification Service (Amazon SNS) can be used to send alerts based on Amazon CloudWatch alarms.", "answer": "True"}, {"question": "The AWS Billing Policy provides information regarding prohibited actions on the AWS infrastructure.","answer": "False"}]
Шаг 2. Создание курса Вопрос
Здесь мы создаем класс с именем Вопрос. Здесь мы используем вопрос как question
и ответ как answer
.
#1 class Question: #2 def __init__(self, question, answer): #3 self.question = question #4 self.answer = answer
Шаг 3. Создание банка вопросов
- Создайте файл с именем main.py.
- Импортируйте словарь question_data из data.py в строке 1.
- Импортируйте класс вопроса из question_model.py в строке 2.
- Создайте пустой список question_bank в строке 4.
- Запустите цикл for в строке 5. Этот цикл for будет циклически перебирать все элементы в словаре question_data.
- В строках 6 и 7 он устанавливает вопрос из наших данных в question_text и 'answer' из наших данных в question_answer .
- Затем в строке 8 он запускает класс вопроса с параметрами question_text и question_answer, устанавливая результат на new_question.
- В строке 9 он добавляет новый_вопрос в наш вопрос_банк.
- При этом будут рассмотрены все наши вопросы и ответы из data.py и они будут добавлены в question_bank.
#1 from data import question_data #2 from question_model import Question #3 #4 question_bank = [] #5 for q in question_data: #6 question_text = q["question"] #7 question_answer = q["answer"] #8 new_question = Question(question_text, question_answer) #9 question_bank.append(new_question)
Шаг 4: Создание класса викторины
- Создайте файл с именем quiz.py.
- Создайте курс Викторина.
- Установите значение по умолчанию 0 для self.question_number и self.score.
- Установите для параметра q_list значение self.question_list. Этот параметр будет задействован позже, когда мы вызовем класс Quiz из нашего файла main.py.
class Quiz: def __init__(self, q_list): self.question_number = 0 self.score = 0 self.question_list = q_list
5. Затем мы создадим метод next_question для класса Quiz непосредственно под нашим предыдущим с таким же отступом, как показано ниже.
6. Строка 2 устанавливает current_question в индекс банка вопросов.
7. Строка 3 добавляет 1 к question_number, поэтому вопросы будут продолжать циклически.
8. Строка 4 принимает ответ пользователя с помощью input () и использует format () для ввода номера вопроса и вопроса.
9. В строке 6 будет проверяться правильность ответа. При добавлении вы увидите синтаксическую ошибку. Позже мы добавим еще один метод, который исправит это.
#1. def next_question(self): #2 current_question = self.question_list[self.question_number] #3. self.question_number += 1 #4. user_answer = input(f"{self.question_number: #5 {current_question.question} (True/False): ") #6. self.check_answer(user_answer, current_question.answer)
10. Добавьте метод Остальные_вопросы, чтобы проверить, меньше ли текущий номер вопроса, чем общее количество вопросов.
def remaining_questions(self): return self.question_number < len(self.question_list)
11. Затем мы проверим ответы и подсчитаем счет с помощью метода check_answer. Это метод, упомянутый в шаге 9 выше.
12. В строке 2, как показано ниже, оператор if заменяет user_answer и answer на нижний регистр для облегчения сравнения и проверяет, равны ли они. Если это так, то в строке 3 он прибавляет 1 к счету и печатает «Отлично, вы все поняли!».
13. Если два ответа не равны, выводится «Ой, вы ошиблись!».
14. Затем строка печатается с использованием функции форматирования, чтобы предоставить правильный ответ в строке 7 и текущий счет пользователя в строке 8. Обратите внимание на отступ следующих двух функций печати , что означает, что они происходят вне оператора if.
#1. def check_answer(self, user_answer, answer): #2 if user_answer.lower() == answer.lower(): #3 self.score += 1 #4 print("Awesome, You got it right!") #5 else: #6 print("Oops, you got it wrong!") #7 print(f"The correct answer was: {answer}") #8 print(f"Your current score is: {self.score}/{self.question_number}\n")
Шаг 5. Завершите quiz-main.py
- Возвращаемся к файлу quiz-main.py. Добавьте следующий код импорта в верхний раздел.
from quiz import Quiz
2. К нашему предыдущему коду мы добавим еще код, который будет продолжать показывать новые вопросы, пока мы не ответим на все доступные вопросы из нашего банка вопросов.
3. Строка 1 ниже берет список question_bank (обсуждаемый на шаге 4 раздела Класс) в Викторина, а затем устанавливает для него значение викторина. Переменная.
4. В строке 3 есть цикл while, который выполняется до тех пор, пока для параметра unknown_questions () установлено значение true, то есть до тех пор, пока номер вопроса меньше количества вопросов. Пока остаются вопросы, next_question () будет запускаться из файла викторины.
5. Когда не останется вопросов, он распечатает строку 7 и строку 8.
#1 quiz = Quiz(question_bank) #2 #3 while quiz.remaining_questions(): #4 quiz.next_question() #5 #7 print("You've completed the quiz") #8 print(f"Your final score was: {quiz.score}/{quiz.question_number}")
Теперь, когда вы запустите quiz-main.py в своем терминале, вам будет предложено ответить на первый вопрос. Поздравляем с созданием викторины!
Полные ресурсы:
quiz-main.py
quiz.py
question_model.py
data.py
question_data = [{ "question": "AWS is more economical than traditional data centers for applications with varying compute workloads because Amazon EC2 instances can be launched on demand when needed.","answer": "True"}, {"question": "AWS Storage Gateway helps migrate databases to AWS quickly and securely.", "answer": "False"}, { "question": "AWS FleaMarket is a digital catalog with thousands of software listings from independent software vendors that makes it easy to find, test, buy, and deploy software that runs on AWS.", "answer": "False"}, {"question": "Amazon VPC lets users provision a logically isolated section of the AWS Cloud where users can launch AWS resources in a virtual network that they define.","answer": "True"}, {"question": "Maintaining physical hardware is an AWS responsibility under the AWS shared responsibility model.","answer": "True"}, {"question": "To deliver content to users with lower latency, Amazon CloudFront uses a global network of points of presence (edge locations and regional edge caches) worldwide.","answer": "True"}, {"question": "Multi-Factor Authentication adds an additional layer of login security to a user's AWS Management Console.", "answer": "True"}, {"question": "AWS X-Ray can identify the user that made the API call when an Amazon EC2 instance is terminated.","answer": "False"}, {"question": "Amazon Simple Notification Service (Amazon SNS) can be used to send alerts based on Amazon CloudWatch alarms.", "answer": "True"}, {"question": "The AWS Billing Policy provides information regarding prohibited actions on the AWS infrastructure.","answer": "False"}]