Skip to main content
 首页 » 编程设计

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

2025年05月04日34小虾米

我成功地构建了一个函数来提示用户提出问题,然后是随机排列的答案选项。但是,由于答案选择现在是随机的,python 如何识别用户输入(数字: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(">>> ") 

请您参考如下方法:

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!