Python 基于文本的随机问题测验
Python text-based random questions quiz
这是一个基于文本的测验示例,其中程序应该给出 5 个问题供用户随机回答。问题是它工作得很好,但只给出了 3 个随机问题,然后就停止了。
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、3 和 5 相同,因此您只有三个独特的问题,因此只显示三个问题。只要 used_questions
的一个元素等于 random_question
,random_question in used_questions
的计算结果为 True;他们不必引用内存中完全相同的列表。
正如评论和其他答案中提到的,洗牌是一种更简单的方法。
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!
一个更简单的方法是使用 shuffle
:
random.shuffle(questions)
这会随机排列您的问题。然后你可以循环 questions
.
这是一个基于文本的测验示例,其中程序应该给出 5 个问题供用户随机回答。问题是它工作得很好,但只给出了 3 个随机问题,然后就停止了。
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、3 和 5 相同,因此您只有三个独特的问题,因此只显示三个问题。只要 used_questions
的一个元素等于 random_question
,random_question in used_questions
的计算结果为 True;他们不必引用内存中完全相同的列表。
正如评论和其他答案中提到的,洗牌是一种更简单的方法。
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!
一个更简单的方法是使用 shuffle
:
random.shuffle(questions)
这会随机排列您的问题。然后你可以循环 questions
.