Python:如何在随机多项选择中跟踪 "correct" 答案

Python: How to track "correct" answer in randomized multiple choice

我成功地构建了一个功能来提示用户提出问题,然后是随机排序的答案选择。但是,由于答案选择现在是随机的,python 如何识别 "correct" 答案的用户输入(数字:1、2、3 或 4)?

import random

def answers():
    answerList = [answer1, answer2, answer3, correct]
    random.shuffle(answerList)
    numberList = ["1: ", "2: ", "3: ", "4: "]
    # A loop that will print numbers in consecutive order and answers in random order, side by side.
    for x,y in zip(numberList,answerList):
        print x,y 

# The question
prompt = "What is the average migrating speed of a laden swallow?"
#Incorrect answers
answer1 = "Gas or electric?"
answer2 = "Metric or English?"
answer3 = "Paper or plastic?"
# Correct answer
correct = "African or European?"

# run the stuff
print prompt
answers()

# Ask user for input; but how will the program know what number to associate with "correct"?
inp = raw_input(">>> ")

我用global关键字和track(list)来检查。但是不知道这样好不好

import random

def answers():
    answerList = [answer1, answer2, answer3, correct]
    random.shuffle(answerList)
    numberList = ["1: ", "2: ", "3: ", "4: "]
    global track
    track = []
    # A loop that will print numbers in consecutive order and answers in random order, side by side.
    for x,y in zip(numberList,answerList):
        print x,y
        track.append(y)





# The question
prompt = "What is the average migrating speed of a laden swallow?"
#Incorrect answers
answer1 = "Gas or electric?"
answer2 = "Metric or English?"
answer3 = "Paper or plastic?"
# Correct answer
global correct
correct = "African or European?"

# run the stuff
print prompt


answers()

# Ask user for input; but how will the program know what number to associate with "correct"?
inp = raw_input(">>> ")

if correct == track[int(inp)-1]:
    print "Success"

else:

    inp = raw_input("Try again>>> ")

为什么不 return answerList 来自您的函数?

那你可以比较一下:

answerList = answers()
inp = raw_input('>>>')

if answerList[int(inp) - 1] == correct:
    print('You're correct!')
else:
    print('Nope...')

list.index求出正确答案的索引:

correct_index = answerList.index(correct)

记住索引是基于 0 的。

我将您的答案放入字典中以保持关联并允许改组问题呈现方式。

import random

def answers(question, possAnswers):
    print(question)
    answerList = ['answer1', 'answer2', 'answer3', 'correct']
    random.shuffle(answerList)
    for i, j in enumerate(answerList):
        print("%s: %s" %(i, possAnswers[j]))
    inp = int(raw_input(">>> "))
    if answerList[inp] == 'correct':
        print('Correct!')
    else:
        print('Incorrect!')

possAnswers = {'answer1' : "Gas or electric?", 'answer2' : "Metric or English?", 'answer3' : "Paper or plastic?", 'correct' : "African or European?"}

question = "What is the average migrating speed of a laden swallow?"

answers(question, possAnswers)

shuffle 的答案列表,但你不应该,你想要做的是洗牌索引列表......一个实施的例子,只是为了澄清我的意思,是

def ask(question, wrong, correct):
    """ask: asks a multiple choice question, randomizing possible answers.

question: string containing a question
wrong:    list of strings, each one a possible answer, all of them wrong
correct:  list of strings, each one a possible answer, all of them correct

Returns True if user gives one of the correct answers, False otherwise."""

    from random import shuffle

    # the add operator (+) concatenates lists, [a,b]+[c,d]->[a,b,c,d]
    answers = wrong + correct

    # we'll need the lengths of the lists, let compute those lengths
    lw = len(wrong)
    lc = len(correct)

    # indices will be a random list containing integers from 0 to lw+lc-1
    indices = range(lw+lc) ; shuffle(indices)

    # print the question
    print question

    # print the possible choices, using the order of the randomized list
    # NB enumerate([1,3,0,2]) -> [(0,1),(1,3),(2,0),(3,2)] so that
    #    initially i=0, index=1, next i=1, index=3, etc
    for i, index in enumerate(indices):
        # print a progressive number and a possible answer,
        # i+1 because humans prefer enumerations starting from 1...
        print "  %2d:\t%s" % (i+1, answers[index])

    # repeatedly ask the user to make a choice, until the answer is
    # an integer in the correct range
    ask = "Give me the number (%d-%d) of the correct answer: "%(1,lw+lc)
    while True:
        n = raw_input(ask)
        try:
            n = int(n)
            if 0<n<lw+lc+1: break
        except ValueError:
            pass
        print 'Your choice ("%s") is invalid'%n

    # at this point we have a valid choice, it remains to check if
    # the choice is also correct...
    return True if indices[n-1] in range(lw,lw+lc) else False

忘了说了,我的例子支持多个正确答案...

你这样称呼它,

In [2]: q = "What is the third letter of the alphabet?"

In [3]: w = [c for c in "abdefghij"] ; c = ["c"]

In [4]: print "Correct!" if ask(q, w, c) else "No way..."
What is the third letter of the alphabet?
   1:   d
   2:   f
   3:   a
   4:   c
   5:   h
   6:   b
   7:   i
   8:   e
   9:   g
  10:   j
Give me the number (1-10) of the correct answer: c
Your choice ("c") is invalid
Give me the number (1-10) of the correct answer: 11
Your choice ("11") is invalid
Give me the number (1-10) of the correct answer: 2
No way...

In [5]: print "Correct!" if ask(q, w, c) else "No way..."
What is the third letter of the alphabet?
   1:   j
   2:   a
   3:   e
   4:   h
   5:   i
   6:   d
   7:   b
   8:   c
   9:   f
  10:   g
Give me the number (1-10) of the correct answer: 8
Correct!