The idea is to have a list with questions.
To get a new question, you
pop()
one element from the list.
To have a list with shuffled questions,
random.shuffle()
will do the job.
Here an overengineered example with typing stuff (not required) and a dataclass.
import random
from dataclasses import dataclass
from typing import List
@dataclass
class Question:
"""
Dataclass to store a question together with
the right answer and wrong answers
"""
question: str
answer: str
wrong_answers: List[str]
def ask_answer(question: str, size: int, exit_answer: str = "q"):
"""
Ask the user to choose an answer and return the integer of answer minus 1.
"""
while True:
value = input(question)
if value.lower() == exit_answer:
return SystemExit
try:
result = int(value)
except ValueError:
print(value, "is not an integer")
continue
if 1 <= result <= size:
return result - 1
else:
print(f"Selection {result} is out of range")
def ask(question: Question):
answers = [question.answer, *question.wrong_answers]
random.shuffle(answers)
print(question.question)
for index, answer in enumerate(answers, 1):
print(f"{index}) {answer}")
choice = ask_answer("Please enter the number of the answer: ", len(answers))
if choice is SystemExit:
return SystemExit
return answers[choice] == question.answer
def game() -> None:
"""
Logic for game
"""
score = 0
print("Question - answer game")
print("Score -1 is allowed")
print("*" * 34)
print()
while questions: # looping until questions is empty
print("Current score:", score)
question = questions.pop()
result = ask(question)
if result is SystemExit:
return
elif result:
score += 1
else:
score -= 1
if score < -1:
print("You lost!")
return
print()
else:
print("No more questions")
print("Score:", score)
questions: List[Question] = [
Question("Your Question 1", "right 1", ["This is wrong", "this also", "..."]),
Question("Your Question 2", "right 2", ["This is wrong", "this also", "..."]),
Question("Your Question 3", "right 3", ["This is wrong", "this also", "..."]),
]
random.shuffle(questions)
if __name__ == "__main__":
try:
game()
except KeyboardInterrupt:
print("Giveup")
If you want to repeat the questions, you need to make a copy from the original list, shuffle the copy and pop the elements from the copy.