2017-09-25 59 views
-5

這是一個基於文本的測驗示例,其中程序應給出5個問題供用戶以隨機順序回答。問題在於它完美地工作,但只給出3個隨機問題,然後停止。Python基於文本的隨機問題測驗

import random 

question1=["The answer is A","A","a"] 
question2=["The answer is B","B","b"] 
question3=["The answer is A","A","a"] 
question4=["The answer is F","F","f"] 
question5=["The answer is A","A","a"] 

questions=[question1,question2,question3,question4,question5] 

used_questions=[] 

while len(used_questions)!=len(questions): 

    random_question=random.choice(questions) 

    while random_question in used_questions: 
     random_question=random.choice(questions) 

    used_questions.append(random_question) 

    print([random_question[0]]) 

    players_answer=input("") 

    if players_answer in random_question: 
     print("\nCorrect!") 
    else: 
     print("\nWrong!") 
+1

你的方法比較複雜,只要做'random.shuffle(問題)'並遍歷問題結果列表(現在以隨機順序) –

+3

因爲你的一些問題是**相同**,所以在三個問題,還沒有問題還沒有被問到。所以你的while while random_questions在used_questions循環中變成了一個無限循環。 – khelwood

回答

1

問題1,3和5是相同的,所以您只有三個獨特的問題,因此只顯示三個問題。只要used_questions的一個元素等於random_questionrandom_question in used_questions的計算結果爲真;他們不必在內存中引用完全相同的列表。

正如在評論和其他答案中所提到的,在這裏洗牌清單是一種更簡單的方法。

import random 

questions=[ 
    ["The answer is A","A","a"], 
    ["The answer is B","B","b"], 
    ["The answer is A","A","a"], 
    ["The answer is F","F","f"], 
    ["The answer is A","A","a"] 
] 

random.shuffle(questions) 
for question in questions: 
    print(question[0]) 
    players_answer=input("") 
    if players_answer in question: 
     print("\nCorrect!") 
    else: 
     print("\nWrong!") 

結果:

The answer is F 
F 

Correct! 
The answer is A 
B 

Wrong! 
The answer is A 
Q 

Wrong! 
The answer is B 
B 

Correct! 
The answer is A 
A 

Correct! 
+0

非常感謝!我可能從來沒有意識到 – VEyeZen

0

一個更簡單的方法是使用shuffle

random.shuffle(questions) 

這打亂您的問題到位。然後你可以循環回到questions