Python Forum
Cannot Assign right Answers To Shuffled Questions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cannot Assign right Answers To Shuffled Questions
#1
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.
Reply
#2
keep questions and answer together in suitable data structure and shuffle the pairs not just questions.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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)
Boblows likes this post
Reply
#4
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]}.')
Boblows likes this post
Reply
#5
How do i prevent same questions to appear?
Reply
#6
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#7
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  'answers 2' is not defined on line 27 0814uu 4 758 Sep-02-2023, 11:02 PM
Last Post: 0814uu
  Division calcuation with answers to 1decimal place. sik 3 2,146 Jul-15-2021, 08:15 AM
Last Post: DeaD_EyE
  Using answers from an input function Totalartist 3 2,221 Jul-19-2019, 02:02 PM
Last Post: snippsat
  Writing Answers From Questionnaire to a new .txt Document FizzyBreak579 4 3,588 Feb-16-2018, 07:26 AM
Last Post: buran
  Discord bot that asks questions and based on response answers or asks more questions absinthium 1 41,873 Nov-25-2017, 06:21 AM
Last Post: heiner55
  Need Answers 20nick20 6 5,448 Apr-29-2017, 04:06 PM
Last Post: Larz60+
  Code that generates MD5 hashes from IPv6 addresses giving differant answers? PyMD5 4 6,488 Oct-17-2016, 02:39 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020