我只是这里的python爱好者,但是我试图编写一个简短的程序,该程序可以根据与列表中的字符串匹配的输入来回答问题。这是我的代码如下:
helloInputs = ["hello", "hi", "hey there", "yo", "hello", ]
howAreInputs = ["how are you", "how are you doing", "how you doing", "how are ya", "sup"]
ageInputs = ["how old are you", "what is your age", "age", "when were you born"]
a = raw_input("Type something here: ")
if a.upper() or a.lower() in helloInputs:
print("Hello there!")
if a.upper() or a.lower() in ageInputs:
print("My name is PySpeechBot. I was made by developer Nicholas A. on June 6, 2020")
if a.upper() or a.lower() in howAreInputs:
print("Im feeling good today! This is actually the only response I am programmed to say back...")
无论如何,我遇到的问题是,当我输入诸如“ Hello”之类的简单内容时,它将以所有可能的答案而不是仅一个回答。再说一次,这里不是最好的程序员,但是如果可以解决这个问题,我将不胜感激。
答案 0 :(得分:0)
如果要检查列表中是否有多个项目,可以使用How to check if one of the following items is in a list?中的解决方案,例如:
if any(x in helloInputs for x in [a.upper(), a.lower()]):
print("Hello there!")
但这并不是您要实现的目标。如果输入列表全部为小写字母,则应删除a.upper()
。
同样,对具有多种可能性的if语句使用elif
,并使用变量而不是一遍又一遍地编写a.lower()
:
a = raw_input("Type something here: ")
b = a.lower()
if b in helloInputs:
print("Hello there!")
elif b in ageInputs:
print("My name is PySpeechBot. I was made by developer Nicholas A. on June 6, 2020")
elif b in howAreInputs:
print("Im feeling good today! This is actually the only response I am programmed to say back...")