如何简化帐户代码?

时间:2017-11-17 15:56:37

标签: python python-3.x simplify

我在python中创建一个帐户代码并且它可以工作,但它确实很长,我想知道是否有办法缩短它。这是我的代码:

user1 = "Jeff"
user2 = "Bob"

password1 = "Password"
password2 = "Lol"

username = input("Login: >> ")
password = input("Password: >> ")

if username == user1:
    if password == password1:
        print ("Access granted")
        print ("Welcome to the system!")
        home()

    else:
        print ("Access denied")
        print ("Try again!")
        print ("\n")
        time.sleep(2)
        login()

elif username == user2:
    if password == password2:
        print ("Access granted")
        print ("Welcome to the system!")
        home()
    else:
        print ("Access denied")
        print ("Try again!")
        print ("\n")
        time.sleep(2)
        login()

else:
    print ("Access denied")
    print ("Try again!")
    print ("\n")
    time.sleep(2)
    login()

我创建的帐户越多,获得的时间就越长。有没有办法缩短或简化这个?

2 个答案:

答案 0 :(得分:0)

以下是您的程序版本,它使用字典存储用户名及其关联密码。这样,您可以向users字典添加更多用户和密码,而无需再添加任何代码。

import time

users = {
    "Jeff": "Password",
    "Bob": "Lol"}

def login():
    username = input("Login: >> ")
    password = input("Password: >> ")
    if username in users and password == users[username]:
        print("Access granted")
        print("Welcome to the system!")
        return True

    print("Access denied")
    print("Try again!")
    print()
    return False

while not login():
    pass

home()

答案 1 :(得分:0)

我将用户和密码检查分开:

users = {
    "Jeff": "Password",
    "Bob": "Lol"}

def login(user=None):

    # User
    if not user:
        user = input("Login: >> ").title()
        if not users.get(user):
            print ("No such user")
            return None

    # Password
    password = input("Password: >> ")
    if password == users[user]:
        print ("Access granted")
        print ("Welcome to the system!")
        return user
    else:
        print("Access denied")
        print("Try again!")
        return login(user=user)

while True:
    logged_in_user = login()
    if logged_in_user:
        print("Welcome {}".format(logged_in_user))
        break