我是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()
到目前为止,据我所知,我创建用于存储对象的数组将被最新的用户输入所取代。因此,我尝试添加一个索引。但是,如果不考虑使用append或insert,则会出现以下错误:“AttributeError:'list'对象属性'insert'是只读的”
question_mcq.insert = [arrayIndex,
questionc(question, option1, option2, option3, answer)
]
insert()
是一个方法,而不是属性。这意味着您必须像调用函数一样调用它因此,在您的情况下,您应该使用
您可以在python3here中阅读有关列表的更多信息
Deshpande012显然有一个正确的解决方案,它提到insert()是一个方法,而不是一个属性。因此,使用不当,必须像函数一样使用。这个答案还包括在代码中直接使用questionc(),而不是为questionc的返回声明一个变量
对于Python多选,您可以选择问题、答案和实际答案,并将它们存储在如下列表中(这是一个非常原始的示例,没有演示正确答案的随机性):
在此基础上,您可以使用Python生成多项选择题测验的代码。无论是在同一个脚本中还是在另一个文件中,对于实际参加用户保存的测验的人来说,这都取决于您!无论采用哪种方式,您都可以清楚地看到使用一组存储的答案和假选项生成Python测验输出是多么简单。您只需要存储问题设置,然后显然能够解释和评估测验答案的分数
https://nerdi.org/programming/python/python-multiple-choice/
Python初学者教程介绍了一些简单的循环和已知的数据结构。然而,为了让本教程更进一步,我真的认为重要的是确保在每次测验中尽可能多地随机排列正确答案。除此之外,我真的认为还值得确保将多项选择测验设置(初始测验创建)存储在数据库或具有更精简数据结构的文件中,您的测验生成器可以轻松读取并使用自己的代码动态使用。当然,从那里你可以考虑存储用户答案,让用户登录来访问他们的测验结果等等。
相关问题 更多 >
编程相关推荐