python - 如何在 Python 中制作注册和登录程序?
问题描述
我正在尝试制作一个人们可以分配用户名和密码然后登录的程序。我正在考虑制作两个功能,一个用于注册,一个用于登录。但是,它似乎无法工作,因为我在注册部分分配了一个用户名,但是当登录功能运行时,它说用户名未定义。你知道我该怎么做吗?
def register():
names=[]
usernames=[]
passwords=[]
names.append(input("Enter your name:"))
usernames.append(input("choose your username:"))
passwords.append(input("choose your password:"))
return usernames
def login(usernames,passwords):
usernames=[]
passwords=[]
password=""
username=""
username=input("Enter your username:")
password=input("Enter your Password:")
if password==passwords[usernames.index(username)]:
print("welcome")
else:
print("incorrect!")
account_ans=""
while True:
account_ans=input("choose: a)Sign Up b)login and shop c)quit")
if account_ans=="a":
register()
if account_ans=="b":
password=""
username=""
usernames=[]
passwords=[]
login(usernames,passwords)
if account_ans=="c":break
解决方案
您的register()
函数返回一个列表对象username
,但您没有将其捕获到变量中,因此它丢失了。register()
因此,一旦功能完成,您输入的所有信息都会消失。
所以 1) 抓住你的回报
if account_ans=="a":
username=register()
当您进入account_ans="b"
代码部分时,您会重置此username
变量以完全清空它。因此,当您传递username
给login()
函数时,它只是一个空列表。您无法登录不存在的人,因此您在此处收到错误。
所以2)不要清空你的username
清单:
if account_ans=="b":
login(usernames,passwords)
当然这里还有更多的问题,但这些是最明显的。我建议不要传递你的username
和password
列表,因为它会让人不知所措地尝试通过意大利面条式的代码来处理它们。而是在代码顶部声明它们并将它们用作全局变量。丹尼尔对同一个问题的回答显示了一个很好的方法来解决这个问题。
最终,这里真正的问题是您无法调试问题。一个好的起点是在其中折腾一些print()
,然后在代码中的不同时间查看这些变量中的内容。您会看到print(usernames)
在错误弹出之前您是否在登录功能内部usernames
执行了代码执行时列表为空的错误。然后你可以回溯并找出为什么usernames
会是空的。在构建此代码时,您将遇到这样的一百万个错误,因此现在学习如何调试将是您成功的关键。
推荐阅读
- javascript - 为什么这个 aysnc 函数没有隐式返回一个承诺?
- amazon-s3 - Github Actions 中的构建过程已完成,退出代码为 2。 -- AWS S3 同步
- excel - Excel - 如何将 VALUETOTEXT() 结果转换回 DATETIME?
- blockchain - 分步教程 - 将 10,000 个独特图像的 ERC721 合约部署到 Opensea
- c++ - 此代码中的各种构造函数调用是什么?
- mysql - varbinary 和 uuid 上的 JDBI 选择
- robotframework - 如何在 Robot Framework 中更改 report.html?
- c++ - 无法在 Eclipse Windows 上编译和运行 MySQL 连接器 C++ 8.0 - 链接器 - MinGW
- android - Android Here Satellite 离线地图
- php - 需要一个项目列表,但输入“dict”PHP