如何简化帐户代码?

How to simplify an account code?

我正在 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()

我创建的帐户越多,它就会越长。有没有办法缩短或简化它?

这是您的程序的一个版本,它使用字典来存储用户名及其关联的密码。这样,你就可以在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()

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

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