首页 > 解决方案 > 如何在 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

标签: pythonfunction

解决方案


您的register()函数返回一个列表对象username,但您没有将其捕获到变量中,因此它丢失了。register()因此,一旦功能完成,您输入的所有信息都会消失。

所以 1) 抓住你的回报

if account_ans=="a":
   username=register()

当您进入account_ans="b"代码部分时,您会重置此username变量以完全清空它。因此,当您传递usernamelogin()函数时,它只是一个空列表。您无法登录不存在的人,因此您在此处收到错误。

所以2)不要清空你的username清单:

if account_ans=="b":
   login(usernames,passwords)

当然这里还有更多的问题,但这些是最明显的。我建议不要传递你的usernamepassword列表,因为它会让人不知所措地尝试通过意大利面条式的代码来处理它们。而是在代码顶部声明它们并将它们用作全局变量。丹尼尔对同一个问题的回答显示了一个很好的方法来解决这个问题。

最终,这里真正的问题是您无法调试问题。一个好的起点是在其中折腾一些print(),然后在代码中的不同时间查看这些变量中的内容。您会看到print(usernames)在错误弹出之前您是否在登录功能内部usernames执行了代码执行时列表为空的错误。然后你可以回溯并找出为什么usernames会是空的。在构建此代码时,您将遇到这样的一百万个错误,因此现在学习如何调试将是您成功的关键。


推荐阅读