如何使循环从列表中获得特定的项目?——python



关于程序:

在这个程序中,我需要首先获得用户的输入以进行"测验"要求拒绝。的问题,然后问问题的文本和4'答案',并从这4个答案中要求正确答案。重复为no。问题。

像一个'quiz maker'

list_of_questions存储问题文本

list_of_keys存储输入的所有问题的"答案"(按顺序)例子:

list_of_keys = [Q1_Answer1, Q1_Answer2, Q1_Answer3, Q1_Answer4, Q2_Answer1, Q2_Answer2, Q2_Answer3, Q2_Answer4, Q3_Answer1 etc...]

在start_quiz()中,我需要首先打印第一个问题文本和4个答案,然后打印第二个问题文本和4个答案等…

使用循环从列表中获取特定项

但是我在下面做的循环:只是再次打印相同的前4个答案。

我找不到正确从列表中获取项目的解决方案。

我尝试了这个,但它没有工作:(超出范围错误)

var1 = 0
for I in main_list:
answer_amount = 4
if answer_amount > 0:
var1 += 1
print(list_of_keys[var1])

整个代码:

from questionclass import Question_template
main_list = []
list_of_questions = []
list_of_answers = []
list_of_keys = []

print("n Quiz maker n")

def make_quiz():
X = 0
Z = 0
Y = 0
amount_of_answers = 4
question_amount = int(input(" Enter number of questions for     your quiz: "))
while question_amount > 0:
question_amount -= 1
X += 1
list_of_questions.append(str(input(" Text for question no." + str(X) + ": ")))
while amount_of_answers > 0:
amount_of_answers -= 1
Y += 1
list_of_keys.append((str(Y) + ".") + str(input("  Answer no." + str(Y) + ": ")))
amount_of_answers = 4
list_of_answers.append(int(input("nwhich answer is the correct answer?n")))
Y = 0
for question in list_of_questions:
main_list.append(Question_template(question, list_of_keys[Z], list_of_answers[Z]))
Z += 1
start_quiz()
def start_quiz():
key = int(input("n enter 0 to start quiz: "))
score = 0
If key == 0:
for question in main_list: 
print(question.promt) # printing the question text
amount_of_answers = 4

for i in list_of_keys:     ####THIS LOOP HERE#### 
if amount_of_answers > 0:
print(i)
amount_of_answers -= 1

answer = int(input(""))
if answer == list_of_answers[0]:
score += 1
makequiz()

问题类:

class Question_template:
def __init__(self, promt, answers, correct):
self.promt = promt
self.answers = answers
self.correct = correct

您每次都得到相同的答案,因为您每次都从list_of_keys的起点进行迭代。问题1在0到4之间迭代,问题2在0到4之间迭代。但是,第二题你的信息在4到8之间。因此,您应该添加一个键计数器来存储您正在查找的问题。因此,我添加了keyCounter,并将每个问题的keyCounter增加到4。除此之外,您还应该从list_of_keys中的那个点开始,例如list_of_keys[keyCounter:].

def start_quiz():
key = int(input("n enter 0 to start quiz: "))
score = 0
keyCounter = 0
if key == 0:
for question in main_list:
print(question.promt) # printing the question text
amount_of_answers = 4
for i in list_of_keys[keyCounter:]:     ####THIS LOOP HERE####
if amount_of_answers > 0:
print(i)
amount_of_answers -= 1
keyCounter = keyCounter + 4

最新更新