我一直在尝试用python制作一个聊天机器人,但是在密码检索过程中,它一直在循环密码输入语句。有解决办法吗?



早些时候,我在getpass命令上遇到了问题,在我解决了这个问题后,没有代码在循环中运行,我的代码如下:

name=str(input("Hello, I am your personal assistant (Assistant Name), please identify yourself"))
while True:
if len(name) !=0:
from getpass import getpass
print("Please Confirm your identity: ")
password=getpass()
if (password == 'root'):
print ('Identity confirmed, welcome back, ',name)
else:
print ('could not verify identity')
else:
print ("could not identify user")
print("What would you like me to help you with today?")

有了这个代码,当我在终端中运行它时,它会询问密码,如果密码不匹配,它就会关闭终端,我不希望发生这种情况,我想要的是,如果密码错误,它应该要求重新输入密码,所以我添加了一个while True语句,即使在这样做之后,如果密码不匹配,终端仍然关闭。此外,如果密码正确,它会给出以下信息:

输出:

Hello, I am your personal assistant, please identify yourself:
input: George
please confirm your identity:
input: root
>>>identity confirmed, welcome back, name
>>>please confirm your identity:
>>>password:

然后它就在密码中循环。我该怎么办?

下面的解决方案应该可以工作,代码中没有退出循环的条件。此外,添加getpass似乎在Pycharm上使用时挂起,在windows控制台中应该可以正常工作。

import getpass
if __name__ == '__main__':
name = str(input("Hello, I am your personal assistant (Assistant Name), please identify yourself"))
pwd_confirmed = 0
while (pwd_confirmed == 0):
print("Please Confirm your identity: ")
password =  getpass.getpass()
if (password == 'root'):
print('Identity confirmed, welcome back, ', name)
pwd_confirmed = 1
else:
print('could not verify identity')
print("What would you like me to help you with today?")

最新更新