我想知道如何制作一个字典,该字典可以存储多个用户输入并在需要时将其打印出来。我已经用这段代码尝试过,但是我猜我错了,因为它不起作用:
def new_questions():
new_question = {}
while new_question:
newly_added_question = raw_input('Please type the question:')
newly_added_question_ans1 = raw_input('Please type the CORRECT answer:')
newly_added_question_ans2 = raw_input('Please type an incorrect answer:')
newly_added_question_ans3 = raw_input('Please type an incorrect answer:')
new_question[newly_added_question] = newly_added_question_ans1
new_question[newly_added_question] = newly_added_question_ans2
new_question[newly_added_question] = newly_added_question_ans3
答案 0 :(得分:0)
您可以尝试列出所有答案的列表并将其存储为:
new_question[newly_added_question] = [newly_added_question_ans1, newly_added_question_ans2, newly_added_question_ans3]
答案 1 :(得分:0)
我建议使用字典来存储=IF(AND(S180>75,V180>75),S180+V180-150,IF(AND(S180>75,V180<75),S180-75,IF(AND(S180<76,V180>75),V180-75,IF(AND(S180<75,V180<75),""))))
字典的每个值,如下所示:
new question
from pprint import pprint
def new_questions():
new_question = True
questions = {}
while new_question:
question = raw_input('Please type the question:')
ans1 = raw_input('Please type the CORRECT answer:')
ans2 = raw_input('Please type an incorrect answer:')
ans3 = raw_input('Please type an incorrect answer:')
answers = {
'correct': ans1,
'incorrect_1': ans2,
'incorrect_2': ans3
}
questions[question] = answers
next_question = raw_input('\nAnother question? (Y/N): ')
if next_question.lower() == 'n':
new_question = False
pprint(questions)
new_questions()
您可以使用Please type the question:How many e's in eternity?
Please type the CORRECT answer:2
Please type an incorrect answer:3
Please type an incorrect answer:42
Another question? (Y/N): y
Please type the question:Is this real?
Please type the CORRECT answer:Yes.
Please type an incorrect answer:No.
Please type an incorrect answer:Maybe?
Another question? (Y/N): n
{"How many e's in eternity?": {'correct': '2',
'incorrect_1': '3',
'incorrect_2': '42'},
'Is this real?': {'correct': 'Yes.',
'incorrect_1': 'No.',
'incorrect_2': 'Maybe?'}}
,questions[question]['correct']
等访问每个问题的答案。
答案 2 :(得分:0)
从您的代码看来,每当您为问题分配新答案时,您似乎都将覆盖字典中键的值。
尝试一些容器来存储密钥的值。也就是说,要在字典中保存问题的答案,您可以将列表用作容器。参见下面的示例。
result = {} #Empty dictionary
def new_question(result):
question = input("Enter the question: ")
ans1 = input("Enter the Correct answer ")
ans2 = input("Enter the Incorrect answer ")
ans3 = input("Enter the another Incorrect answer ")
answers = [ans1,ans2,ans3] #storing answers in a list
result[question] = answers #setting answers to question
new_question(result) #add questions and answers by calling this fuction, call this in a loop if multiple questions
print(result) # print all the questions and answers
注意:如果您定义了答案的选项数量,那么您也可以为用户输入添加循环。