因此,我一直在使用python 3.7开发一个基本的bot,我正在开发一个关闭功能。当用户键入单词“ shutdown”或“ Shutdown”时,机器人会确认您是否真的要关闭程序。
对于“是:和”否“命令,我将所有命令存储在列表中。现在,当我使用自己创建的程序时,它仅适用于列表中的第一项,而不适用于其他项。如下:
import time
shutdownAnswerYes = ["Yes", "yes", "Ye", "ye", "Y", "y"]
shutdownAnswerNo = ["No", "no", "nah", "nope", "N", "n"]
shutdown = "shutdown"
while True:
question = input("What do you want to do?: ")
if question == shutdown:
shutdownAnswer = input("Are you sure you want to shutdown?: ")
if shutdownAnswer == shutdownAnswerNo[0]:
print("Got it! Resuming back to normal mode.")
elif shutdownAnswer == shutdownAnswerYes[0]:
print("Got it! Shutting down.")
time.sleep(1)
exit("Shutdown Complete.")
如果尝试运行此代码,您会注意到,如果键入“是”或“否”(列表中的第一项),程序将正常运行。但是,如果您在列表中键入其他任何项目,例如“是”或“否”,则将无法使用。
我也通过更改[]括号中的数字来尝试此代码,但它不起作用。
您刚刚检查了索引为0的第一个元素。
import time
shutdownAnswerYes = ["Yes", "yes", "Ye", "ye", "Y", "y"]
shutdownAnswerNo = ["No", "no", "nah", "nope", "N", "n"]
shutdown = "shutdown"
while True:
question = input("What do you want to do?: ")
if question == shutdown:
shutdownAnswer = input("Are you sure you want to shutdown?: ")
if shutdownAnswer in shutdownAnswerNo:
print("Got it! Resuming back to normal mode.")
elif shutdownAnswer in shutdownAnswerYes:
print("Got it! Shutting down.")
time.sleep(1)
exit("Shutdown Complete.")
在python列表中,以下将起作用,并检查用户输入是否匹配:
if shutdownAnswer in shutdownAnswerNo:
或
if shutdownAnswer in shutdownAnswerYes:
您应该这样重写If块代码:
if shutdownAnswer in shutdownAnswerNo:
print("Got it! Resuming back to normal mode.")
if shutdownAnswer in shutdownAnswerYes:
print("Got it! Shutting down.")
time.sleep(1)
exit("Shutdown Complete.")
将'=='更改为'in'
if shutdownAnswer in shutdownAnswerNo:
if shutdownAnswer in shutdownAnswerYes: