Python Forum
Cannot Assign right Answers To Shuffled Questions - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Cannot Assign right Answers To Shuffled Questions (/thread-32116.html)



Cannot Assign right Answers To Shuffled Questions - Boblows - Jan-21-2021

Hello guys,just started coding with python and come up with an idea of writing multiple choice exam wich shuffles the questions with random.shuffle if you want to resolve it again...

Everything goes fine until code shuffles the questions but i cant assign answer choices to the questions so as questions shuffle answer choices stays the same

For example Question 1 has A) 1 B)2 C)3 D)4 E)5 when code shuffles the questions Question 1 becomes Question 2 but answer choices stays the same.


RE: Cannot Assign right Answers To Shuffled Questions - buran - Jan-21-2021

keep questions and answer together in suitable data structure and shuffle the pairs not just questions.


RE: Cannot Assign right Answers To Shuffled Questions - deanhystad - Jan-21-2021

A dictionary is a natural for storing exam questions.

exam = {Q1:A1, Q2:A2, Q3:A3...QN:AN}

Each Q:A is an item with a key (Q) and value (A).

Dictionaries work almost anywhere lists work. You could use the random library to make a pop quiz from you exam questions.

pop_quiz = random.sample(exam, k=5)


RE: Cannot Assign right Answers To Shuffled Questions - BashBedlam - Jan-22-2021

You only need to shuffle the references to the questions and answers not the questions them selves. Observe :

from random import randint

questions = ['What is 2 plus 2?',
		'Why is there air?',
		'Who wrote the book of love?']

answers = ['a) 1\nb) 2\nc) 3\nd) 4',
		'a) To Breath\nb) To fly kits\nc) To fill volley balls\nd) All of the above',
		'a) Donald Trump\nb) BashBedlam\nc) The Monotones\nd) God']

correct_answers = ['d', 'd', 'c']

question_number = randint (0, 2)
print (questions [question_number])
print (answers [question_number])
print (f'The answer is {correct_answers [question_number]}.')



RE: Cannot Assign right Answers To Shuffled Questions - Boblows - Jan-22-2021

How do i prevent same questions to appear?


RE: Cannot Assign right Answers To Shuffled Questions - DeaD_EyE - Jan-22-2021

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.


RE: Cannot Assign right Answers To Shuffled Questions - buran - Jan-22-2021

Actually there is no need to pop(). pop() will reindex the list you pop from. This would not make difference for small list, but is good to know. It's enough to shuffle the list and iterate over shuffled list. In case you need less than all questions - just break out of the loop.