我该如何使用我的代码(Python登录系统)?

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

我是新编码员。这是我的第一个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")
python python-3.x
1个回答
0
投票

您可以将凭据放在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')
© www.soinside.com 2019 - 2024. All rights reserved.