我想写一个程序,允许用户输入问题和答案的多项选择测验。问题和答案需要以json格式写入一个文件。你知道吗
到目前为止,我有一个代码,它会问用户一个问题,问题的正确答案,然后3个不正确的答案,并将所有字符串写入一个文件。但是我不知道如何将字符串转换成json以便在测验中使用。你知道吗
到目前为止,我掌握的代码是:
def addToList(filename, data):
question = input('Add Question: ') # prompt user to type what to add
correct = input('Add Correct Answer: ')
wrong1 = input('Add 1st Incorrect Answer: ')
wrong2 = input('Add 2nd Incorrect Answer: ')
wrong3 = input('Add 3rd Incorrect Answer: ')
question = question + '\n' # add a line break to the end
correct = 'correct: ' + correct
wrong1 = 'wrong1: ' + wrong1
wrong2 = 'wrong2: ' + wrong2
wrong3 = 'wrong3: ' + wrong3
data.append(question) # append the question
data.append(correct)
data.append(wrong1)
data.append(wrong2)
data.append(wrong3)
f = open(filename, 'a') # open the file in append mode
f.write(question) # add the new item to the end of the file
f.write(correct)
f.write(wrong1)
f.write(wrong2)
f.write(wrong3)
f.close()
抱歉,我知道这是一个新手的问题,但我完全迷失在这里,找不到任何用户输入被放入Json的例子。你知道吗
首先构建一个
dictionary
,然后将其转换为JSON
。你知道吗像这样:
相关问题 更多 >
编程相关推荐