Search code examples
pythonpython-3.x

How to store user input in Python and call it later?


I want to make a program that remembers something and can show it later on - like A.I.

First, I will show the program the question, like "How are you today?" and I also teach it the answer "Fine , you?", something like that.

Second, when I ask the program "How are you today?" or "How are you?", it should know the answer.

So far, I have this:

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= ")

What should I do to be able to store the question, the answer for the respective question, then, when I input something like "Password" or any specific word to be able to test if it knows to reply my questions?


Solution

  • Try a dictionary data structure. This structure allows fast retrieval of a value (answer) given a key (question). Here's a sample program and output:

    # dictionary to store the question-answer pairs
    qa = {}
    
    # store a series of question/answer pairs
    while True:
        question = input("add a question (or q to quit): ")
    
        if question == "q": 
            break
    
        answer = input("add the answer: ")
        qa[question] = answer
        
    print("...")
    
    # run the quiz
    while True:
        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...")
    

    Sample run:

    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
       
    

    If you need to persist these questions beyond the program's run, write your qa dict to a file or store the questions and answers in a database such as SQLite.