我已经写了这个非常简单的代码,应该响应特定的用户输入。我知道我做错了什么,但我不知道是什么。当我键入一个词或留白时,我得到的答复是“无”。提前感谢:) 这是我的代码:
import random
# Sentences we'll respond with if the user greeted us
GREETING_KEYWORDS = ("hello", "hi", "greetings", "sup", "whats up", "You")
GREETING_RESPONSES = ["sup buddy", "Hola", "Halo", "Hi back?"]
def check_for_greeting(sentence):
"""If any of the words in the user's input was a greeting, return a greeting response"""
if sentence is not None:
for word in sentence:
if word.lower() in GREETING_KEYWORDS:
return random.choice(GREETING_RESPONSES)
else:
pass
elif sentence is None:
return "You got to say something if you want me to do the same."
else:
return "Something is wrong..."
def chat_input():
x = input("")
print(check_for_greeting(x))
# Run
print("chat with me...")
chat_input()
如果这些单词都不在
GREETING_KEYWORDS
中怎么办?那还什么呢?当发生这种情况时,没有显式的return
语句,所以答案是:None
被返回。在如果
^{pr2}$for
循环完成而没有找到问候语,则可以通过返回默认响应来解决此问题。在下一个问题是
for word in sentence
迭代句子的每个字母,而不是每个单词。要重复单词,请将句子分开:接下来,我看到您想要检测两个单词的问候语:
whats up
。这是行不通的,因为把句子分成单词意味着你只能检查一个单词的问候语。我建议颠倒逻辑:循环所有可能的问候语,看看它们是否在句子中。(请注意,现在您不想将句子拆分为单词。)最后,这有点高级,但是可以使用生成器表达式加上
any()
将检查简化为一个简单的if/else。在我喜欢这个,因为它读起来更像普通英语。在
相关问题 更多 >
编程相关推荐