python - Python将多个用户输入存储在一个对象中,然后是数组
问题描述
我是 python 新手。
据我了解,我试图让用户使用类和对象创建自己的多项选择题。
我创建了一个类
class questionc:
def __init__ (self, question, option1, option2, option3, answer):
self.question = question
self.option1 = option1
self.option2 = option2
self.option3 = option3
self.answer = answer
此后,我尝试创建一种方法来要求用户输入他们的问题。
from question import *
question_mcq= [
]
def createMCQ():
noOfQuestions = int(input("How many questions are there in total: "))
arrayIndex = 0
while noOfQuestions != 0:
question = input("Type in your question: ")
option1 = input("Enter your MCQ choices: ")
option2 = input("Enter your MCQ choices: ")
option3 = input("Enter your MCQ choices: ")
answer = input("Enter the correct answer: ")
question_mcq= [
questionc(question, option1, option2, option3, answer)
]
#questionMix = questionc(qeustion, option1, option2, option3, answer)
#question_mcq.insert = (arrayIndex, questionMix)
noOfQuestions -= 1
arrayIndex += 1
for number in range(len(question_mcq)):
print(question_mcq[number].question)
print(question_mcq[number].option1)
print(question_mcq[number].option2)
print(question_mcq[number].option3)
#userAnswer = input("Enter you option 1, 2 or 3")
createMCQ()
截至目前,据我了解,我为存储对象而创建的数组将被最新的用户输入替换。因此,我尝试添加索引。但是,不管使用追加还是插入,都会出现错误:“ AttributeError: 'list' object attribute 'insert' is read-only”
question_mcq.insert = [arrayIndex,
questionc(question, option1, option2, option3, answer)
]
解决方案
Deshpande012 肯定有正确的解决方案,提到 insert() 是一种方法,而不是属性。所以使用不当,必须像函数一样使用。这个答案还包括在代码中直接使用 questionc() 而不是为 questionc 的返回声明一个变量。
question_mcq.insert(arrayIndex, questionc(question, option1, option2, option3, answer))
对于 Python 多项选择,您可以获取问题、答案和实际答案,并将它们存储在如下列表中(这是一个非常原始的示例,没有展示答案改组或正确答案的随机性):
questions = {
"What is 15*3?":{"correct":"a", "answers":[45,35,60,40,30]},
"What is 17 * 2?":{"correct":"b", "answers":[43,34,36,32,30]},
"What is 19 * 3?":{"correct":"e", "answers":[58,48,55,59,57]},
"What is 22 * 7?":{"correct":"c", "answers":[168,152,154,156,161]}
}
从那里,您可以使用 Python 生成多项选择测验的代码。对于实际参加用户保存的测验的任何人来说,这是否发生在同一个脚本或另一个文件中取决于您!无论哪种方式,您都可以清楚地看到使用一组存储的答案和虚假选项来生成 Python 测验输出是多么简单。您只需要存储问题设置,然后显然能够解释和评估测验答案的分数。
https://nerdi.org/programming/python/python-multiple-choice/
初学者 Python 教程使用一些简单的循环和已知的数据结构涵盖了所有内容。但是,为了使本教程更进一步,我真的认为确保正确答案在每次测验时尽可能多地随机排列是很重要的。除了该更改之外,我确实认为值得确保您将多项选择测验设置(初始测验创建)存储在数据库或具有更纤薄数据结构的文件中,您的测验生成器可以轻松读取和使用自己的代码动态使用。当然,您可以从那里考虑存储用户答案、让用户登录以访问他们的测验结果等。
推荐阅读
- expressionengine - 规范 URL 问题
- c++ - 为什么这个指针为空
- google-maps - 没有 javascript 对象的 GeoJSON - 可以绘制 InfoWindow 吗?
- angular - 我不能用量角器自动化 Angular 项目
- javascript - 根据Google表格脚本第一列中合并单元格中的日期从表格锁定异常中删除行
- r - 想要获取基于因子列偏离平均值的值的数据框
- azure-active-directory - 改善公司内部员工的 SSO 体验,同时访问受 Azure AD B2C 保护的消费者应用程序
- sql - 在 SQL 中将 CHAR 转换为 int 会导致错误
- python - 通过python json模块更新json文件无法通过discord命令工作
- com - 返回属性时未设置错误对象变量或块变量