This code is about making replies always appear in a different order in a message. But in the process everything gets mixed up.
A random.choice
event for each of the answers (A, B, C, D)
and the questions was created. I would like however only that the answer possibilities remain random
, speak:
1st attempt:
(9 is correct here)
A) 9
B) 8
C) 7
The answer given is "A", correct.
2nd run-up:
A) 8
B) 9
C) 7
Now "B" is given as the answer, that should also be counted as correct. How do I proceed?
My code:
question_one = "How many lives do cat's have?"
answers_one = {"9": "A", "1": "B", "10": "C"}
questions = {question_one: {"9": answers_one}, "Is this working now?": {"A": {"Yes!": "A",
"No!": "B", "Maybe...": "C"}}}
# get a question
question = random.choice(list(questions.keys()))
data = questions.get(question)
correct_answer = list(data.keys())[0]
answers = list(list(data.values())[0].items())
question_msg = ""
answers_msg = ""
numbers_list = []
answers_list = []
for answer, number in answers:
numbers_list.append(number)
answers_list.append(answer)
while numbers_list:
num = numbers_list
ans = random.choice(answers_list)
answers_msg += f "**{num}) {ans}**\n"
answers_list.remove(ans)
numbers_list.remove(num)
My attempt was simply to remove the random
function, but accordingly there is then no more list and nothing can be selected. My attempt to create a list also failed.
Iterating through a list while removing or adding items to it is considered a bad practice.
You can use random.shuffle
to shuffle the list and randomise how the options are displayed.
Another thing I noticed in your code was
questions = {"How many lives do cat's have?": {"9": {"9": "A", "1": "B", "10": "C"}}, "Is this working now?": {"A": {"Yes!": "A","No!": "B", "Maybe...": "C"}}}
In the first item, you are using 9
as the answer and in the second item, you are using A
as the answer. If my understanding of your question is correct, you should be using A
as the key for the first item. This is where you are probably going wrong.
The correct implementation:
options = ['A', 'B', 'C', 'D'] # if you want more options use string.ascii_uppercase
questions = {"How many lives do cat's have?": ['9', ['9', '1', '10']], "Is this working now?": ['Yes!', ['Yes!', 'No!', 'Maybe...']]}
question = random.choice(list(questions.keys()))
data = questions.get(question)
answer_options = data[1].copy()
random.shuffle(answer_options)
answer = data[0]
answer_option = options[answer_options.index(answer)] #gets correct option from options
answer_msg = ""
for i, option in enumerate(answer_options):
answer_msg += f"{options[i]}) {option}"
#check if user input is equal to answer_option