需要帮助的 Python 初学者
我的程序是一个对错测验,用户输入保存的数据,分为两部分。
第 1 部分:程序询问用户有多少个问题。然后,用户填写该金额的一系列问题和答案。如果为问题提供的答案不是(真)或(假),则程序会重新要求答案。然后,用户保存以使用此数据,以便在第 2 部分中进行学习。
def vf():
import pickle
import random
import os
os.system('cls')
v = input("How many questions do you have : ")
vvff = list()
for i in range(0, int(v)):
v = input("Enter question : ")
while True:
f = input("Enter answer to that question (true or false) : ")
if f.lower() in ('true', 'false', 'True', 'False'):
continue
else:
print("This answer is invalid, please enter True or False")
vf = {"question": v, "answer": f}
vvff.append(vf)
question_vff = input("Would you like to save (yes or no) ")
if (question_vff == 'yes'):
pickle.dump(vvff, open("Save.dat", "wb"))
print("Saved!")
if (question_vff == 'no'):
print ("Please save to use you're data.")
第 2 部分:用户使用之前保存的数据来回答正确或错误的测验。该测验随机排列问题和答案,用户回答每个问题。如果用户答对了,程序会说干得好,如果用户答错了,程序会说答案错误。
def vf2():
import pickle
import random
import os
os.system('cls')
vvff = pickle.load(open("Save.dat", "rb"))
random.shuffle(vvff)
for f in vvff:
print(f["question"])
response = input("What was the answer to that question? : ")
if (response == f["answer"]):
print("Good answer!")
else:
print("Wrong answer...")
print("The answer is", f, ".")
print("The study/quiz session is now over. Either create new data or try again later.")
我的问题是,在第 2 部分中,程序应该从保存的数据中打乱问题,并向用户询问每个问题。但是,它只询问他们在程序第 1 部分中输入的最后一个问题。造成这种情况的原因是什么以及如何解决?非常感谢您的帮助。
最佳答案
这里有一些小错误,所以我会一次性改正:
def vf():
import pickle
import random
import os
os.system('cls')
n = input("How many questions do you have : ") #Changed v to n to avoid overlap
vvff = list()
for i in range(0, int(n)):
v = input("Enter question : ")
while True:
f = input("Enter answer to that question (true or false) : ")
if f.lower() in ('true', 'false'): #removed capitals, it's already lowercase
continue
else:
print("This answer is invalid, please enter True or False")
vf = {"question": v, "answer": f} #Moved inside for-loop
vvff.append(vf) #Moved inside for-loop
question_vff = input("Would you like to save (yes or no) ")
if (question_vff == 'yes'):
pickle.dump(vvff, open("Save.dat", "wb"))
print("Saved!")
if (question_vff == 'no'):
print ("Please save to use you're data.")
关于Python 初学者(需要帮助) - 程序仅输出已保存列表的一个元素 (3.8.1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59978232/