寻找更好的方式来编写“凭据验证程序”

问题描述 投票:0回答:1

我刚刚开始学习Python(使用Python 3.12.1) 我想编写一段代码,使用存储在元组中的一堆凭据来验证用户输入的用户名和密码。

我对每个用户名和密码使用每个元组。 我也有他们的每个条件。 它有效,但每次我添加更多元组时,条件只会不断增长

我希望能够编写更少的条件来验证所有用户使用元组的输入。

class credential():
    def __init__(self, username, password):
        self.user = (username, password)

serah = credential('serah','0168')
bob = credential('bob','0110')
kevin = credential('kevin','0440')

def log_in():
    name_input = input('Username: ')
    password_input = input('Password: ')
    verify = (name_input, password_input)
    if verify == serah.user:
        print('hello ',name_input)
    elif verify == bob.user:
        print('hello ',name_input)
    elif verify == kevin.user:
        print('hello ',name_input)
    else:
        print(False)
        
user_input = log_in()

提前致谢。

python-3.x conditional-statements tuples user-input
1个回答
0
投票

蒂姆的评论是正确的,但是为了解决您特别提到的问题,您有几个选择:

迭代。将所有用户保留在一个迭代器中。迭代抛出它们并找到完全匹配的。这不是一个省时的解决方案,并且无法扩展。

哈希表。创建一个哈希表(在Python中称为字典),将用户名作为键和密码。如果输入的用户名存在于“数据库”中,则获取其值(即密码)并与输入的密码进行比较。如果匹配则登录成功,否则登录失败。

© www.soinside.com 2019 - 2024. All rights reserved.