Python If,Else在检查函数是否为真时不起作用
我是Python编程的初学者。最近,我决定构建一个音频助手(基本上是一个带有音频的聊天机器人),但在尝试生成输出时遇到了一个问题。我编写代码的方式是,如果用户说/要求bot做的事情,是bot没有定义的事情,或者如果给出了特定参数,它没有任何关于该做什么的命令,那么它应该给出一个特定的输出。其代码如下:Python If,Else在检查函数是否为真时不起作用,python,if-statement,chatbot,Python,If Statement,Chatbot,我是Python编程的初学者。最近,我决定构建一个音频助手(基本上是一个带有音频的聊天机器人),但在尝试生成输出时遇到了一个问题。我编写代码的方式是,如果用户说/要求bot做的事情,是bot没有定义的事情,或者如果给出了特定参数,它没有任何关于该做什么的命令,那么它应该给出一个特定的输出。其代码如下: # to take input from the user: command = input("Whatever you want to say: ") command = command.low
# to take input from the user:
command = input("Whatever you want to say: ")
command = command.lower()
cmd = command.split()
# below are the commands to give output after processing the input
if 'hi' in cmd:
print('hey')
elif (('how')and('are'))and('you') in cmd:
print('All good! Wbu?')
elif (('hi')and('hru')) in cmd:
print('Hey! Everyting is fine! Wbu?')
else:
print('sorry, did not understand what you meant!')
上面代码的问题是,如果用户说:(嗨,hru?)程序只会说:嗨。
这是因为我在程序中使用了elif语句。所以我决定将所有语句都改为if语句:
if 'hi' in cmd:
print('hey')
if (('how')and('are'))and('you') in cmd:
print('All good! Wbu?')
if (('hi')and('hru')) in cmd:
print('Hey! Everyting is fine! Wbu?')
else:
print('sorry, did not understand what you meant!')
这样做的目的是,它很好地打印输出,但是如果任何其他语句的输出应该被给出,它给出了该语句,但也给出了其他语句的输出
然后我尝试为输出定义一个函数,如果它是真的,即如果用户所说的有指定的输出,那么它应该给出输出,如果没有,那么程序应该打印异常
def commands():
if 'hi' in cmd:
print('hey')
if (('how')and('are'))and('you') in cmd:
print('All good! Wbu?')
if (('hi')and('hru')) in cmd:
print('Hey! Everyting is fine! Wbu?')
if commands()==True:
commands()
else:
print('sorry, did not understand what you meant!')
这也是第一个,打印语句和异常。如何解决这个问题?尽管在英语(和其他人类语言)中说这样的话很常见: 如果X和Y在Z中 …这不是布尔逻辑的工作原理 您实际编写的内容的解析更像这样:
if ('hi' in cmd) and ('hru' in cmd):
如果X和Y在Z中
类似于('hi'和'hru')
的东西会给你一个无用的结果()
您需要的是:
如果X在Z,Y在Z
要完成此操作,请按如下方式重写您的条件:
if ('hi' in cmd) and ('hru' in cmd):
在主程序中,我是按照您所说的方式编写的,只是为了简单起见,我还是按照我的方式编写的,尽管很抱歉,这根本不能解决我的问题:-(那么你的意思是,你有一个问题,当你问这个问题时,你给出的唯一的问题描述是完全不同的代码?哇,谢谢你浪费了我的时间。)(