Home > Software engineering >  How to generate random questions and corresponding answers for quiz game?
How to generate random questions and corresponding answers for quiz game?

Time:04-05

I'm making a quiz game and i want questions to be randomly generated. The problem is i dont know how to make corresponding answers to questions and how to make them not to repeat. Also problem is that i get columns by index in in the answers

questions = [("Was Einshtein a genius?", "B"), ("How old is Putin?", "C"), ("What is my favourite dish?", "D"),
 ("Why i broke up with my girl?", "A" )]

 answers =   [["A. He is a fool", "B. Definetly", "C. He's stupid", "D. He's a gay"],
  ["A. 65", "B. 48", "C. 69", "D. 61"],
  ["A. Pizza", "B. KFC Chicken", "C. Big tasty", "D. Lazania"],
  ["A. She cheated on me", "B. She stole my phone", "C. She broke my phone", "D. She broke ,y heart"]]

ques_ran = random.randint(0,3)
for i in questions:
    print(questions[ques_ran])
    for key in answers:
        print(key[ques_ran])
    b = input('Enter an asnwer ')

I expect that each of these four questions with corresponding answers will display randomly and they won't repeat(there should be all 4 present questions with answers displaying for 4 iterations, one question on one iteration)

CodePudding user response:

Trying to keep multiple lists "in sync" always makes things more complicated. Things will be easier if you combine the question, possible answers, and correct answer into a class, then put instances of that class into a single list.

Then you can use random.shuffle or random.sample to randomize your list of questions while avoiding duplicates.

CodePudding user response:

Build a list that contains both the questions and answers. There are lots of better ways to do this, but a quick fix given your current separate lists is to just zip them together. Then you can use random.choice to select a single question/answer pair, or random.shuffle to iterate through all of them in random order, etc.

q, a = random.choice(list(zip(questions, answers)))
print(q[0])
print(a)
if input() == q[1]:
    print("Correct!")
else:
    print("Wrong!")

CodePudding user response:

A possible implementation, if you want to ask all questions in a random order without repeats, could be to list all indices and shuffle them:

import random
order = list(range(len(questions)))
random.shuffle(order)

for i in order:
    print(questions[i][0])
    print('\n'.join(answers[i]))
    ans = input('answer: ')
    print('correct' if ans == questions[i][1] else 'incorrect')

NB. I would probably use a different logic to store the data though. Probably a single container with question, choices, correct answer.

  • Related