Python 为啥我的列表只能识别一组登录详细信息?

Posted

技术标签:

【中文标题】Python 为啥我的列表只能识别一组登录详细信息?【英文标题】:Python Why can my list only recognize one set of login details?Python 为什么我的列表只能识别一组登录详细信息? 【发布时间】:2017-11-24 00:19:24 【问题描述】:

我尝试制作一个存储用户名和密码的登录详细信息存储程序。我设法使它在登录设法识别第一组登录详细信息的地方部分工作,但是,我的 login() 函数似乎无法识别已附加到列表的第二组登录详细信息。基本上,如果我在保管库列表中附加一些密码,例如“qwerty”、“123456”、“2017”,它将只接受第一个密码,而不接受第二个或第三个密码。如何让程序接受更多登录详细信息,而不仅仅是一组?任何帮助将不胜感激。

vault = []
appvault = []
passvault = []

def menu(): 
    mode = input("""Hello , below are the modes that you can choose from:\n
    ##########################################################################
    a) Login with username and password
    b) Register as a new user
    To select a mode, enter the corresponding letter of the mode below
    ##########################################################################\n
    > """).strip()
    return mode

def login():
    if len(vault) > 0 : #user has to append usernames and passwords before it asks for login details
        print("Welcome to the login console")
        while True:
            username = input ("Enter Username: ") 
            if username == "":
                print("User Name Not entered, try again!")
                continue
            password = input ("Enter Password: ") 
            if password == "":
                print("Password Not entered, try again!")
                continue
            try:
                for i in vault: 
                    if i[username] == password:
                        print("Username matches!")
                        print("Password matches!")
                        logged() #jumps to logged function and tells the user they are logged on
                        break 
            except KeyError: #the except keyerror recognises the existence of the username and password in the list
                print("The entered username or password is not found!")

    else:
        print("You have no usernames and passwords stored!")

def register(): #example where the username is appended. Same applies for the password
    print("Please create a username and password into the password vault.\n")

    while True:
        validname = True
        while validname:
            username = input("Please enter a username you would like to add to the password vault. NOTE: Your username must be at least 3 characters long: ").strip().lower()
            if not username.isalnum():
                print("Your username cannot be null, contain spaces or contain symbols \n")
            elif len(username) < 3:
                print("Your username must be at least 3 characters long \n")
            elif len(username) > 30:
                print("Your username cannot be over 30 characters \n")
            else:
                validname = False 
        validpass = True

        while validpass:
            password = input("Please enter a password you would like to add to the password vault. NOTE: Your password must be at least 8 characters long: ").strip().lower()
            if not password.isalnum():
                print("Your password cannot be null, contain spaces or contain symbols \n")
            elif len(password) < 8:
                print("Your password must be at least 8 characters long \n")
            elif len(password) > 20:
                print("Your password cannot be over 20 characters long \n")
            else:
                validpass = False #The validpass has to be True to stay in the function, otherwise if it is false, it will execute another action, in this case the password is appended.
        vault.append(username:password)
        validinput = True
        while validinput:
            exit = input("\nEnter 'end' to exit or any key to continue to add more username and passwords:\n> ")
            if exit in ["end", "End", "END"]:
                break
            else:
                validinput = False
                register()
        return register

def logged():
    print("----------------------------------------------------------------------\n")
    print("You are logged on.")

while True:
        chosen_option = menu() #a custom variable is created that puts the menu function into the while loop

        if chosen_option in ["a", "A"]:
            login()

        if chosen_option in ["b", "B"]:
            register()

        else:
            print("""That was not a valid option, please try again:\n """)

【问题讨论】:

您为什么使用listdicts?问题是你得到一个KeyError 并继续在循环外,因为每次你尝试检查第二组或第三组登录详细信息时,它在第一次迭代时失败if i[username] == password:为什么不保留dict 的登录详细信息? 或者,至少,将该行包含在 try-except 中,而不是整个 for 循环。 【参考方案1】:

您正在循环通过 listdicts。将 vault 更改为 dict,并去掉 for 循环:

vault = 

def login():
    if len(vault) > 0 : #user has to append usernames and passwords before it asks for login details
        print("Welcome to the login console")
        while True:
            username = input ("Enter Username: ") 
            if username == "":
                print("User Name Not entered, try again!")
                continue
            password = input ("Enter Password: ") 
            if password == "":
                print("Password Not entered, try again!")
                continue
            try:
                if vault[username] == password:
                    print("Username matches!")
                    print("Password matches!")
                    logged() #jumps to logged function and tells the user they are logged on
                    break 
            except KeyError: #the except keyerror recognises the existence of the username and password in the list
                print("The entered username or password is not found!")

    else:
        print("You have no usernames and passwords stored!")

您将不得不从

替换 register() 中的附加内容
vault.append(username:password)

vault[username] = password

另一方面,我建议不要存储实际密码,而是存储哈希值。看看here。

【讨论】:

以上是关于Python 为啥我的列表只能识别一组登录详细信息?的主要内容,如果未能解决你的问题,请参考以下文章

为啥我的 Spring 应用程序无法识别有人已经登录?

为啥我的平移手势只能在第二次输入后识别事件?

为啥 Angular 无法识别用户是不是使用 keycloak 登录?

我的vncviewer远程登录Linux为啥只能用root帐号登录

Python初学者,为啥我爬取的网页数据输出列表没对齐

为啥 Python 不能识别我的 utf-8 编码源文件?