如何sipmlify我的代码(Python登录系统)?

2024-06-28 11:21:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我是个新的编码员。这是我第一次使用python登录系统代码。如何简化代码而不丢失任何功能,如错误的用户名和密码等

username = "zaphod"
password = "helloworld42"
username2 = "mozzie"
password2 = "mozzietheaussie"
userUsername = input("Hello, What is your username? \n")
UserPassword = input(print("Hello", userUsername, "What is your password? "))
if userUsername == username:
    if password == UserPassword:
        print("Hello", userUsername, "Welcome home")
if userUsername == username:
    if UserPassword != password:
        print("Wrong Password")
if userUsername == username2:
    if UserPassword != password2:
        print("Wrong Password")
if UserPassword == password:
    if userUsername != username:
        print("Wrong Username")
if UserPassword == password2:
    if userUsername != username2:
        print("Wrong Username")
if userUsername == username2:
    if UserPassword == password2:
        print("Hello", userUsername,"Welcome Home")
if userUsername == username:
    if UserPassword == password2:
        print("Are you gonna trick me pal xd")
if userUsername == username2:
    if UserPassword == password:
        print("Are you gonna trick me pal xd")
if userUsername != username:
    if userUsername != username2:
        if UserPassword != password:
            if UserPassword != password2:
                print("Wrong credidentals")

Tags: 代码helloinputyourifisusernamepassword
1条回答
网友
1楼 · 发布于 2024-06-28 11:21:16

您可以将凭据放在dict中,并检查用户名是否存在以及是否与密码匹配

credentials = {'zaphod': 'helloworld42',
           'mozzie': 'mozzietheaussie'}

user_name = input('Hello, what is your username?\n')
password = input(f'Hello {user_name}, what is your password?\n')

pas = credentials.get(user_name) # returns None if the user name doesn't exists
if not pas:
    print('Wrong Username')
elif pas != password:
    print('Wrong Password')
else:
    print(f'Hello {user_name}, welcome home')

print("Are you gonna trick me pal xd")似乎没有必要,但是您可以通过修改elif来添加它

elif pas != password:
    if password in credentials.values():
        print('Are you gonna trick me pal xd')
    else:
        print('Wrong Password')

相关问题 更多 >