[英]how to make a loop to get specific items from a list? - python
關於程序:
在這個程序中,我需要獲得用戶的輸入以進行“測驗”,首先要求否。 問題,然后詢問問題文本和 4 個“答案”,並從這 4 個答案中要求正確答案。 重復沒有。 的問題。
像一個“測驗制作者”
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:
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 之間迭代。 但是,對於問題 2,您的信息介於 4 到 8 之間。因此,您應該添加一個密鑰計數器來存儲您要查找的問題。 因此,我添加了 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.