繁体   English   中英

为什么我在python中循环索引无法给我正确的输出

[英]Why my for looping an index in python not give me correct output

我是python的新手,我正在尝试进行基本的登录帐户检查,并且某种程度上,我的代码没有显示我想要的内容。 我已经定义了三个用户名,并且当我运行代码时,如果第一次输入不正确的用户名,则代码显示帐户不会退出,但是不建议您这样做。 我不知道为什么

我认为这是我的for循环问题,因为当我输入错误的帐户时,我的i索引从0开始,一直循环直到结束索引,然后比较输入的用户名和列表中存在的用户名。 然后在比较所有索引后,如果找不到用户名,则表明打印帐户不存在,我尝试解决此问题,但找不到正确的方法。

user1=[  
   {'id':'0001','name':'123','password':'a123', 'balance':0.00},
   {'id':'0002','name':'456','password':'a456', 'balance':0.00},  
   {'id':'0003','name':'789','password':'a789', 'balance':0.00}
]

for x in range(0,4):

    name = input('User Name:')
    for i in range(len(user1)):
        if name == user1[i]['name']:  
            password = input('Password:')
            if password == user1[i]['password']:  
                print("Success login")
        continue
        if name != user1[i]['name']:
            print("Account not exist, input new one")

如果输入错误的用户名; 它应该显示帐户不存在,请输入新密码,然后输入用户名456,然后询问正确的密码。

看一下循环体的逻辑:

for i in range(len(user1)):
    if name == user1[i]['name']:  
        password = input('Password:')
        if password == user1[i]['password']:  
            print("Success login")
    continue
    if name != user1[i]['name']:
        print("Account not exist, input new one")

无论输入什么内容,您都永远不会到达第二条if语句: if程序到达该点,就告诉它continue下一次循环迭代。 尝试以下方法:

for i in range(len(user1)):
    if name == user1[i]['name']:  
        password = input('Password:')
        if password == user1[i]['password']:  
            print("Success login")
        else:
            print("Account not exist, input new one")

请注意,如果您将所有帐户都放在一个字典中,这样做会更好,因此您可以直接访问它们:

user1 = {
   '123': {'id':'0001', 'password':'a123', 'balance':0.00},
   '456': {'id':'0002', 'password':'a456', 'balance':0.00},  
   '789': {'id':'0003', 'password':'a789', 'balance':0.00}
}

这样,您就可以按名称直接访问每个帐户,而不用在整个列表中搜索尝试登录的用户。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM