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

2024-05-28 23:34:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个程序,可以记住一些东西,然后再显示出来,比如人工智能

首先,我向程序显示一个问题,比如“你今天怎么样?”我也教它答案“好吧,你?”,差不多。在

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

到目前为止,我有这个:

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

我应该怎么做才能存储问题,相应问题的答案,然后,当我输入类似“密码”或任何特定的单词来测试它是否知道回答我的问题?在


Tags: the答案answer程序inputsadeda
2条回答

你可以使用字典。在

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

尝试使用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...")

输出:

^{pr2}$

相关问题 更多 >

    热门问题