用户名和密码代码

时间:2017-08-14 04:06:06

标签: python passwords username

我在python3.6中编写了一个用户创建用户名和密码的程序。然后程序检查是否存储了该用户名,如果没有它永久地创建用户名和密码。我无法将用户名和密码列表链接为“jason'有密码' oero'。

这样

if sentence == stored_username[0:] and sentence2 == stored_password[0:]:
    print(Aceppted)
&p> jason'是用户名,oero是密码。

另一个问题是,当我运行程序时,它试图运行整个列表,因此你不能只选择一个列表值。这就是我到目前为止所拥有的。如果用户的用户名和密码错误3次,该程序也将被设置为退出。哪个工作正常。谢谢!代码按原样运行,也就是假设的方式。

username= input('Create Username')
password= input('Create Password')
stored_username =['jason' , 'nicole',username]
stored_password =['oeros', 'chance',password]

print(stored_username[0:])

trials =0
def sign_in():
    global username
    global password
    global stored_username

    global stored_password


    sentence= input('Enter Username')
    print(sentence)
    sentence2 = input('Enter Password')
    print(sentence2)
    global trials
    Aceppted= 'Welcome to Bacall Land'
    wrong=('Wrong Username or Password ')

    if sentence == stored_username[0:] and sentence2 == stored_password[0:]:
        print(Aceppted)
    else:
        print(wrong)
    while sentence != stored_username[0:] and sentence2!= stored_password[0:]:
        trials += 1
        print(trials)
        (trials <=3 and sign_in())
        if trials >= 3:
            break
    if sentence== stored_username[0:] and sentence2 == stored_password[0:]:
        print(Aceppted)
    else:
        quit()




sign_in()

2 个答案:

答案 0 :(得分:0)

首先,将字符串用户名/密码与整个列表进行比较:

 sentence == stored_username[0:] and sentence2 == stored_password[0:]

当您对像stored_username[0:]这样的列表进行切片时,它会返回从元素0开始到列表末尾的子列表。您需要先使用stored_username.index(sentence)获取用户名的索引,然后获取相同索引的密码。但是,使用字典可以使这更简单,更快速,更容易阅读。以下是使用字典存储用户名/密码的示例:

stored_users = {'jason': 'oeros', 'nicole': 'chance'}
accepted = 'Welcome to Bacall Land'
wrong = 'Wrong username or password'

def add_user():
    print('Creating user, please choose username and password')
    username = input('Username: ')
    password = input('Password: ')
    if stored_users.get(username):
        print('Username already exiss')
    else:
        stored_users[username] = password

def login():
    print('Logging in')
    username = input('Username: ')
    password = input('Password: ')
    if stored_users.get(username) == password:
        return True
    else:
        print False

trials = 0
add_user()
while trials < 3:
    check = login()
    if check:
        print(accepted)
        break
    else:
        print(wrong)

答案 1 :(得分:0)

问题在于,无论输入,if sentence == stored_username[0:] and sentence2 == stored_password[0:]:都返回false,是吗?

这是因为您正在检查输入和列表之间的相等性,它将始终返回false,即'jason' == ['jason' , 'nicole',username]将始终返回false。

要解决此问题,可以使用in运算符,即: if sentence in stored_username[0:] and sentence2 in stored_password[0:]:

此外,[0:]切片是多余的,因为它返回整个列表,因此您可以编写: if sentence in stored_username and sentence2 in stored_password:

相关问题