Python检查列表的开头,直到找到正确的项,但是我向它显示了从哪个位置开始?

2024-10-02 00:44:05 发布

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

    AccountU = ['Cam', 'Copper']
    AccountP = ['Pop1234', 'What?']

    def LoginA():
        print ("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
        print ("A few clicks away from your selection!")
        UserE = input("Username: ")
        if UserE in AccountU:
            for position, UserE in enumerate(AccountU):
                PasswordF = AccountP[position]
                PassE = input("Password: ")
                if PasswordF == PassE:
                    Menu()
        else:
            print ("Your account is not working.")
            LoginA()

在这段代码中,我试着让它输入用户名,然后找出位置。这应该允许它与密码交叉检查,因为它们将在同一时间输入。但是,它从一开始就交叉检查,直到检查正确的位置

例如,如果我为用户名输入“Copper”,那么它会询问密码两次,即使我输入了“What?”。我认为这可能与“for position,UserE in enumerate(AccountU):”有关,但我对“for position,UserE in enumerate(AccountU):”非常困惑

要求输入两次密码的证明

Proof of requiring to enter the password twice.


Tags: in密码forinputifpositionwhatprint
2条回答

问题在于

           for position, UserE in enumerate(AccountU):
                PasswordF = AccountP[position]
  1. 您正在覆盖UserE
  2. 您正在询问每个用户的密码

设置if条件并检查用户输入的密码

           for position, User in enumerate(AccountU):
                if UserE == User:
                    PasswordF = AccountP[position]
                    .... your code ......

使用字典是更好的选择

您不需要循环查看AccountU中的每个条目—您知道要查找哪个用户名,只需要相应的密码。如果使用.index()方法,可以在AccountU列表中找到用户名的索引。然后,假设AccountPAccountU直接匹配,您可以在同一索引中找到正确的密码,如下所示:

AccountU = ['Cam', 'Copper']
AccountP = ['Pop1234', 'What?']

def LoginA():
    print ("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
    print ("A few clicks away from your selection!")
    UserE = input("Username: ")
    if UserE in AccountU:
        PasswordF = AccountP[AccountU.index(UserE)]
        PassE = input("Password: ")
        if PasswordF == PassE:
            Menu()
        else:
            print ("Incorrect Password")
    else:
        print ("Your account is not working.")
        LoginA()

不过,最好使用字典来存储用户名和密码。这将确保正确的用户与正确的密码匹配。下面是一个如何工作的例子:

accounts = {'Cam': 'Pop1234',
            'Copper': 'What?'}

def LoginA():
    print ("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
    print ("A few clicks away from your selection!")
    UserE = input("Username: ")
    if UserE in accounts.keys():
        PassE = input("Password: ")
        if accounts[UserE] == PassE:
            Menu()
        else:
            print ("Incorrect Password")
    else:
        print ("Your account is not working.")
        LoginA()

相关问题 更多 >

    热门问题