Dec-02-2020, 06:16 AM
You would get a lot of benefit from writing some classes to manage your test and questions. Something like this (but much better):
import random class Question: def __init__(self, question=''): self.question = question self.answers = [] self.correct_answer = 0 def ask(self): while True: print(f'\nQuestion: {self.question}') for i, answer in enumerate(self.answers): print(f'{i+1}: {answer}') try: answer = int(input('Enter answer: ')) if not answer in range(1, len(self.answers)+1): raise ValueError return answer except ValueError: print('Please enter the number of your answer') def print(self): print(f'\nQuestion: {self.question}') for i, answer in enumerate(self.answers): print(f'{i+1}: {answer}') print(f'Correct answer : {self.correct_answer}') def make_quiz(): quiz = [] while True: text = input('Enter question: ') if len(text) == 0: return quiz q = Question(text) while len(q.answers) < 4: text = input(f'Enter answer {len(q.answers)+1}: ') if len(text) > 0: q.answers.append(text) elif len(q.answers) < 2: print('There must be at least two answers') else: break; # done entering answers q.correct_answer = q.ask() q.print() if input('Add this question to the quiz? (y/n): ')[0] in ('Yy'): quiz.append(q) def take_quiz(quiz): questions = random.sample(quiz, k=len(quiz)) score = 0 for q in questions: answer = q.ask() if answer == q.correct_answer: score += 1 else: print(f'The correct answer is {q.correct_answer}: {q.answers[q.correct_answer-1]}') print('\n\n') print(f'Your score is {score} out of {len(questions)}') print('Enter questions for the quiz') quiz = make_quiz() print('\n\nTake the quiz') take_quiz(quiz)You would want a way to store a quiz in a file and load a quiz from a file. You might want a way to edit a quiz, though it may be easier to just edit the quiz file. Unless the file is encrypted.