我的代码:
def make_response(self):
recognised = False
get_cmd = False
database = {
"hello": "Nice to meet you. What can I do for you?",
"hi": "Nice to meet you. What can I do for you?",
"hey": "Nice to meet you. What can I do for you?",
"goodbye": "Bye. See you next time!"
}
self = self.lower()
for i in database:
if i in self:
recognised = True
value = database.get(i)
print(value)
def robot():
print('Welcome to robot.py')
print('What can I do for you?')
while True:
query = input('>')
make_response(query)
robot()
当我输入“ hello”时,程序给出了预期的响应,但是它只是退出而没有完成循环。哪条线打破了循环? 谢谢。
答案 0 :(得分:1)
在Python 3.x中,可以正常工作。
也许您正在使用python 2.x进行编译。在这种情况下,您需要使用“ raw_input”而不是“ input”,但是我不建议使用raw_input(在Python3中已弃用)。
尝试使用Python 3.x。
PS:另外,我将“ self”替换为其他变量名称。自我用于课堂。
答案 1 :(得分:0)
我完全无法复制。就像代码说的那样,它不断提示输入新内容。
顺便说一句,使用dict.items()
进行了一些简化:
database = {
"hello": "Nice to meet you. What can I do for you?",
"hi": "Nice to meet you. What can I do for you?",
"hey": "Nice to meet you. What can I do for you?",
"goodbye": "Bye. See you next time!",
}
def make_response(query):
query = query.lower()
for keyword, answer in database.items():
if keyword in query:
print(answer)
break
def robot():
print("Welcome to robot.py")
print("What can I do for you?")
while True:
query = input(">")
make_response(query)
robot()
答案 2 :(得分:0)
它没有破裂。请验证您的解决方案。这是修改后的代码
database = {
"hello": "Nice to meet you. What can I do for you?",
"hi": "Nice to meet you. What can I do for you?",
"hey": "Nice to meet you. What can I do for you?",
"goodbye": "Bye. See you next time!"
}
def make_response(self):
self = self.lower()
value = database.get(self, "Sorry I dont understand")
print(value)
def robot():
print('Welcome to robot.py')
print('What can I do for you?')
while True:
query = input('>')
if query == "goodbye":
value = database.get(query)
print(value)
break
else:
make_response(query)
robot()
答案 3 :(得分:0)
此代码在我的机器上完美运行。但是Python 2.7版本存在问题。我希望您使用Python 3.6或更高版本。
这是一个简化的代码。
代码:
def make_response():
database = {
"hello": "Nice to meet you. What can I do for you",
"hi": "Nice to meet you. What can I do for you?",
"hey": "Nice to meet you. What can I do for you?",
"goodbye": "Bye. See you next time!"
}
return database
def robot():
print('Welcome to robot.py')
print('What can I do for you?')
while True:
query = str(input('>'))
database = make_response()
if query in list(database.keys()):
print(database[query])
robot()
检查一下。 希望对您有所帮助。