我成功构建了一个函数来提示用户提问,然后是随机排序的答案选项。但是,由于答案选择现在是随机的,因此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(">>> ")
答案 0 :(得分:3)
你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!
答案 1 :(得分:2)
为什么不从你的函数返回answerList?
然后你可以比较:
answerList = answers()
inp = raw_input('>>>')
if answerList[int(inp) - 1] == correct:
print('You're correct!')
else:
print('Nope...')
答案 2 :(得分:0)
我使用全局关键字和跟踪(列表)来检查。但不知道这是不是一个好习惯
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>>> ")
答案 3 :(得分:0)
使用list.index
查找正确答案的索引:
correct_index = answerList.index(correct)
请记住,索引是基于0的。
答案 4 :(得分: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)