如何在python中存储用户输入并稍后调用它?

时间:2018-06-03 20:40:47

标签: python python-3.x

我想制作一个能够记住某些东西的程序,并且可以在以后显示它 - 比如A.I.

首先,我向程序展示问题,例如“你今天过得怎么样?”我也教它答案“很好,你呢?”,就像那样。

第二,当我问节目“今天你好吗?”或者“你好吗?”,它应该知道答案。

到目前为止,我有这个:

    print ("Salut ! Am nevoie de ajutorul tau sa invat cateva propozitii...")
print ("Crezi ca ma poti ajuta ?")
answer1 = input("da/nu")

if (answer1=="da"):
  print ("Bun , acum tu poti sa pui intrebarea si raspunsul")
  print ("Spre exemplu , Primul lucru la inceput de linie trebuie sa fie intrebarea urmata de *?* ")
  print ("Apoi , raspunsul pe care eu trebuie sa il dau.")
  print ("Exemplu : Intrebare= Ce faci ? Raspuns= Bine , mersi :D")
question= "asd"
while (question != "stop"):
  question = input("The question: ")
  answer = input("The answer= ")

我应该怎么做才能存储问题,相应问题的答案,然后,当我输入类似“密码”或任何特定单词的内容时,如果它能够测试它是否知道回答我的问题?< / p>

2 个答案:

答案 0 :(得分:1)

尝试dictionary数据结构。这种结构允许在给定密钥(问题)的情况下快速检索值(答案)。这是一个示例程序和输出:

# dictionary to store the question-answer pairs
qa = {}

# store a series of question/answer pairs
while 1:
    question = input("add a question (or q to quit): ")

    if question == "q": 
        break

    answer = input("add the answer: ")
    qa[question] = answer

print("...")

# now quiz your program
while 1:
    question = input("ask me a question (or q to quit): ")

    if question == "q": 
        break
    elif question in qa:
        print(qa[question])
    else:
        print("i'm not sure...")

输出:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

add a question (or q to quit):  what is the meaning of life?
add the answer:  42
add a question (or q to quit):  what is my password?
add the answer:  1234
add a question (or q to quit):  q
...
ask me a question (or q to quit):  what is the meaning of life?
42
ask me a question (or q to quit):  what is my password?
1234
ask me a question (or q to quit):  help?
i'm not sure...
ask me a question (or q to quit):  q

答案 1 :(得分:0)

您可以使用词典

answers = dict()
# usage is answers[question] = answer;
answers['How are you?'] = 'Good'
question = input()
if question in answers:
 print(answers[question])