我正在尝试创建一个数学游戏,它从我的列表中随机选择一个问题并给出相应的答案。目前,我可以将问题随机化,然而,它从列表中按顺序给出答案,而不是对应于问题的答案。 如何得到随机问题的答案是正确的。 这是我的代码。
import random
counter = 0
score = 0
incorrect = 0
name=input("What is your name?")
print("Hi",name,",welcome to your math quiz!")
questions = ["10*2","4-2","6+12","6*4","12-5","6+54","1*0","3-6","4+0","65-9"]
answers=["20","2","18","24",'7','60','0','-3','4','56']
idx_questions = list(enumerate(questions))
idx_answers = list(enumerate(answers))
random.shuffle(idx_questions)
for idxq, question in idx_questions:
print(question)
ans = input("What is the answer? ")
for idxa, answer in idx_answers:
if idxq == idxa and ans == answer:
print("Correct")
score=score+1
print("Correct Answers=",score)
print("Incorrect Answers=",incorrect)
elif idxq == idxa and ans != answer:
print("Incorrect", answers)
incorrect=incorrect+1
print("Correct Answers=",score)
print("Incorrect Answers=",incorrect)
print("End of quiz")
print(name,"your score is",score,"out of 10")
print(score*10,"%")
答案 0 :(得分:0)
import random
counter = 0
score = 0
incorrect = 0
questions = ["10*2","4-2","6+12","6*4"]
answers=["20","2","18","24"]
idx_questions = list(enumerate(questions))
idx_answers = list(enumerate(answers))
random.shuffle(idx_questions)
for idxq, question in idx_questions:
print(question)
ans = input("What is the answer? ")
for idxa, answer in idx_answers:
if idxq == idxa and ans == answer:
print("Correct")
elif idxq == idxa and ans != answer:
print("Incorrect")
答案 1 :(得分:0)
问题是你洗牌问题列表,而答案列表保持不变。所以现在答案和问题,有一个不同的位置,他们不匹配。相反,您应该只在该索引处生成随机索引和打印问题。
random_int = random.randint(0, len(questions)-1)
print(question[random_int])
当然你应该建立一些机制来阻止相同的答案弹出两次。一种方法是删除用过的问题。
del questions[random_int]
del answers[random_int]
答案 2 :(得分:-1)
您的代码的问题是使用random.shuffle()
函数。
它以随机的方式对您的问题列表进行随机播放(基本上是围绕列表中的元素进行交换),因此您对应的特定索引答案将与问题列表不匹配。
这个答案应该更清楚:https://stackoverflow.com/a/976918/8750461
相反,您可能希望使用q = random.choice(questions)
来获取随机问题,然后使用answers[questions.index(q)]
获取相应的答案。
可能有更优雅的解决方案,这只是一个快速的答案。